I'm working through the Automate the Boring Stuff with Python Course on YouTube/udemy, and I'm on a lesson that covers a simple number guessing game. LINK
The code itself I more or less understand:
# 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 one and a ONE HUNDRED.')
secretNumber = random.randint(1, 100)
for guessesTaken in range(1, 7):
print('Take a guess.')
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is for correct guesses!
if guess == secretNumber:
print('Good job, ' + name + ', You took ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '. You Failed!')
You take a random integer between 1 and 100. The user tries to guess it. If they get it right, it tells you. If you're unable within a certain number of guesses, you lose.
I wanted to add a 'try' 'except' statement to deal with a non-integer input that the user might make. It took me a while to get around the syntax errors, but I managed to write:
for guessesTaken in range(1, 7):
print('Take a guess.')
try:
guess = int(input())
except ValueError:
print ("That's not an integer!")
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is for correct guesses!
This produces the correct error message. However, it produces another 'NameError' because guess is now not properly defined.
How should I amend the flow statements to get me back to the point where the program allows me to input a different value?