简体   繁体   English

为什么我会收到 NameError?

[英]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"我不知道为什么我会得到这个:NameError: name 'guess' is not defined,即使我在“func1”中定义了它

You're getting the error because guess only exists in the scope of func1() .您收到错误,因为guess仅存在于func1()的范围内。 You need to return the value guess from func1() to use it.您需要从func1()返回值guess才能使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM