import sys, random
def rand():
number = random.randint(0, 100)
def start():
print("Entrez un nombre et essayez de faire correspondre le nombre aléatoire")
guess= int(input())
def check():
print (guess, number)
if guess == number:
print ("Les nombres sont le même!")
print ("Recomence?")
reawn=str(input())
if reawn == "oui":
rand()
start()
check()
elif guess < number:
print ("Ton nombre est plus grands que le nombre aléatoire!")
print ("Essaye encore?")
reawn=str(input())
if reawn == "oui":
start()
check()
elif guess > number:
print ("Ton nombre est plus petit que le nombre aléatoire!")
print ("Essaye encore?")
reawn=str(input())
if reawn == "oui":
start()
check()
rand()
start()
check()
Traceback (most recent call last): File "F:\Dominic\Python\rando.py", line 36, in check() File "F:\Dominic\Python\rando.py", line 10, in check print (guess, number) NameError: name 'guess' is not defined
在Python中,在函数外部定义的变量不能在函数内部访问。同样,函数内部定义的变量不能在函数外部或另一个函数内部访问。例如
如果你运行这个程序,它会
因为这三个
f
要么在函数外部,要么在函数内部,所以它们都不相同。在程序中,在check()
中使用guess
和number
,即使这些变量是在start()
和rand()
中定义的。为了能够在任何地方访问这些变量,在程序开始时,必须将以便能够从程序的任何地方访问这些变量。必须在定义变量之前放置这些。 另一种解决方法是在程序结束时
在
rand()
函数中,将return number
放在末尾,在start()
函数中,将return guess
放在末尾。另外,您必须在check()
的参数中这允许
check()
函数在其参数中获取number
和guess
,而不必使变量全局化你的问题与局部变量和全局变量之间的差异有关
这里,在函数
check()
中,您引用的是局部变量guess
,它只在另一个函数start()
中定义,没有在函数check()
的上下文中定义。函数check()
不知道变量guess
,除非您指定它在函数中等于什么在这种情况下,您可以做的是:
下面是Python文档中关于全局和局部变量的more information
变量
guess
是函数start
的局部变量。这意味着其他函数看不到它。考虑从start
返回:同样的语句也适用于函数
rand
(从函数返回随机数)然后更改
check
的定义如下:最后,启动程序如下:
相关问题 更多 >
编程相关推荐