Ashikur Rahman
Ashikur Rahman

Reputation: 23

How to solve python string format?

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!")

Upvotes: 0

Views: 76

Answers (1)

Chris
Chris

Reputation: 22993

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.

Upvotes: 1

Related Questions