うちわ 密か うちわ 密か - 2 months ago 15
Python Question

Why am I getting NameError?

Here's a part of the the code I'm trying to run:

def func1():
a = True
while a == True:
try:
guess = int(input("guess it: "))
a = False
except ValueError:
print("Not a valid number.")

import random
number = random.randint(0, 50)
print("Im thinking of a number between 0 and 50,")

func1()

if guess == number:
print("Perfect, you got it from the first try!")


I don't know why I get this: NameError: name 'guess' is not defined, even though I defined it in "func1"

Answer

You're getting the error because guess only exists in the scope of func1(). You need to return the value guess from func1() to use it.

Like so:

def func1():
    a = True
    while a == True:
        try:
            guess = int(input("guess it: "))
            a = False
        except ValueError:
            print("Not a valid number.")
    return guess # i'm returning the variable guess

import random
number = random.randint(0, 50)
print("Im thinking of a number between 0 and 50,")

guess = func1() # I'm assigning the value of guess to the global variable guess

if guess == number:
    print("Perfect, you got it from the first try!") 
Comments