2016-09-10 97 views
2

这里的代码的一部分,我试图运行:为什么我得到NameError?

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:名字“猜”是没有定义的,即使我定义为“ func1“

+5

'guess'是该函数的在'func1'功能,这意味着它ðoesn't存在*外部的本地名称*。 if语句永远不会到达,因为你有编程错误。 –

+0

你可能想[重新阅读函数的Python教程](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)。如果您想与您的程序的其余部分共享“猜测”值,则需要“返回”该值。 –

+0

谢谢先生,非常感谢。 –

回答

1

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