为什么我会收到NameError?

时间:2016-09-10 16:24:59

标签: python python-3.5

这是我尝试运行的代码的一部分:

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

我不知道为什么会这样:NameError:name' guess'没有定义,即使我在" func1"中定义了它。

1 个答案:

答案 0 :(得分:1)

您收到错误是因为guess仅存在于func1()的范围内。您需要从guess返回值func1()才能使用它。

像这样:

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