这是我的代码:
import time
def guessit():
print('i have a number from 0 to 10 and you must guess it!')
guess = input("what's the number?")
if guess == a: # this is the global variable specified in the function "randomnumber"#
print('you cheater! how did you know? fine, you win!')
else:
print('you failed! i win! would you like to play again?')
randomnumber()
def randomnumber():
global a
a = random.randint(0, 10)
guessit()
randomnumber()
这里是一些上下文:
这是游戏,用户猜出一个从十到十的数字。
问题:
打印值a
没问题,这是评估它的问题。每当我尝试这样做时,甚至通过打印a
值进行复制粘贴,仍然会给我else
评估结果。
我尝试输入local
(相反,global
是python中的关键字),但是没有像其他任何关键字一样突出显示。
执行时是否有任何方法可以使全局变量a
成为函数内部的局部变量?
欢迎来到网站!否。该变量需要在全局范围内定义:
a = 7 # 7 for example
import time
def guessit():
global a
print('i have a number from 0 to 10 and you must guess it!')
guess = input("what's the number?")
if guess == a: # this is the global variable specified in the function "randomnumber"#
print('you cheater! how did you know? fine, you win!')
else:
print('you failed! i win! would you like to play again?')
randomnumber()
def randomnumber():
global a
a = random.randint(0, 10)
guessit()
randomnumber()
您未正确使用global
关键字。它没有定义新变量,仅声明该函数将使用预定义的全局变量。
希望这会有所帮助!如果您有任何问题,请告诉我。