0

I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!

#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()

print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)

#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
    guess = int(input())
    if type(guess) != int:
        print ("You did not enter a number, please re-enter")
        continue


    if guess < secretNumber:
        print ("The number you guessed was too low")
    elif guess > secretNumber:
        print ("The number you guessed was too high")
    else:
        break

if guess == secretNumber:
    print ("Oh yeah, you got it")
else:
    print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))

print ("You took " + str(guessesTaken) + " guesses.")
Mike Müller
  • 82,630
  • 20
  • 166
  • 161

2 Answers2

1

Use a try and except:

for guessesTaken in range(1, 7):
    try:
        guess = int(input())
    except ValueError:
        print ("You did not enter a number, please re-enter")
        continue

So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Thank you for the suggestion. This no longer returns an error however, when continue executes, it still only allows 6 tries (guessesTaken? –  Dec 07 '17 at 19:30
  • Yes, the loop is finished after six tries with a wrong input. – Mike Müller Dec 07 '17 at 20:17
0

You can try a simple while loop that waits until the user has entered a digit. For example,

guess = input("Enter a number: ") # type(guess) gives "str"

while(not guess.isdigit()):  # Checks if the string is not a numeric digit
    guess = input("You did not enter a number. Please re-enter: ")

That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).

You can then convert the digit to an integer as before:

guess = int(guess)

For example, consider the following cases:

"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer