0

I wrote the below code for a simple math. As I know it should work perfectly. But I'm getting an error with the string format. The shell showing a message that "NameError: name 'guess' is not defined". But the variable is already defined there though.

import random
import re

#select a random number
myNumber = random.randint(1, 20)


#loop for the game
while True:
    try:
        guess = int(input("Guess a number and put here : "))
    except ValueError:
        print("not a number {}".format(guess))
    else:
        if not guess in range(1, 20):
            print('Put only number between 1 - 20')
            continue
        elif guess == myNumber:
            print("that's right")
            break
        else: 
            print("Bummer!")
1
  • If the user enters something that's not a number, int() will throw an exception instead of returning a value, and therefore guess is not defined when you try to print its value in the except clause. Commented Jul 9, 2017 at 23:40

1 Answer 1

1

guess will only be defined if no error is raised in the try clause. Thus, when an error is raised, guess will never be defined, and Python will raise a NameError. You need to give guess a default value before the try/except block. Or, as @John Gordon has mentioned, you can get the user input outside of the for loop, and only attempt to redefine as an integer inside of the try clause.

Sign up to request clarification or add additional context in comments.

2 Comments

Or retain the original string input as a separate value, and print that in the except message.
@JohnGordon Yes, that would also work. And that would perhaps be a better option if the OP doesn't want to predefine guess as an integer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.