python - 为什么我会收到 NameError?

标签 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' is not defined, even though I defined it in "func1"

最佳答案

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

像这样:

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

关于python - 为什么我会收到 NameError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39428155/

相关文章:

python - decimal.Decimal(n) % 1 返回 InvalidOperation, DivisionImpossible for all n >= 100

python - numpy 选择不同长度的每一行

python - 无法在 Python 中使用正则表达式检索所有组

python - 在我的本地盒子上运行我的 django webapp 时,为什么我使用 firefox 7.0.1 时出现黑屏

python - 为反向 View 传递 kwargs; Django 1.5

Python 从输出变量中搜索字符串并打印接下来的两行

python - 如何在 Python 中打印线条

python - 我应该将 Python 3.5 降级到 3.4 吗?

java - 将 Java UDP 接收器转换为 Python

python - Sublime Text 2 上的模块错误