Seth Bowyer
Seth Bowyer

Reputation: 11

how to add an error message when an integer is input instead of a string

I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.

import random

number = random.randrange(1, 50)

while True:
    try:
    guess = int ( input("Guess a number between 1 and 50: ") )
    break
except ValueError:
    print("Please input a number.")**
  

while guess != number:
    if guess < number:
        print ("You need to guess higher. Try again.")
        guess = int ( input("\nGuess a number between 1 and 50: ") )
    else:
        print ("You need to guess lower. Try again.")
        guess = int ( input("\nGuess a number between 1 and 50: "))

print ("You guessed the number correctly!")

Upvotes: 0

Views: 7763

Answers (3)

Anshumaan Mishra
Anshumaan Mishra

Reputation: 1362

You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int. Sample code:

a = input()
while not a.isnumeric():
    a = input('Enter a valid integer')
a = int(a)

The code executes until the value of a is an int

Upvotes: 1

Tomerikoo
Tomerikoo

Reputation: 19414

Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the guess to a default value that will never be equal to the number (None) and use one single input, wrapped with try/except:

import random

number = random.randrange(1, 50)
guess = None  

while guess != number:
    try:
        guess = int(input("Guess a number between 1 and 50: "))
    except ValueError:
        print("Please input a number.")
    else:
        if guess < number:
            print("You need to guess higher. Try again.")
        elif guess > number:
            print("You need to guess lower. Try again.")

print("You guessed the number correctly!")

Upvotes: 2

Rohith Nambiar
Rohith Nambiar

Reputation: 3730

your code did not work because the indentation is not right

import random

number = random.randrange(1, 50)
while True:
    try:
        guess = int ( input("Guess a number between 1 and 50: ") ) # here
        break # here
    except ValueError: # here
        print("Please input a number.")
  

while guess != number:
    if guess < number:
        print ("You need to guess higher. Try again.")
        guess = int ( input("\nGuess a number between 1 and 50: ") )
    else:
        print ("You need to guess lower. Try again.")
        guess = int ( input("\nGuess a number between 1 and 50: "))

print ("You guessed the number correctly!")

Output

Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.

Upvotes: 0

Related Questions