下面的代码在执行时显示了错误,在执行Looper()之前,我不是在第二行中执行了辅助吗?但是,当我在Looper()的第一行中添加chances=5时,它就起作用了
import random
chances = 5
def Looper():
if chances != 0:
if real_answer == user_answer:
print("Gotcha")
exit()
elif real_answer < user_answer:
chances -= 1
print("Too large")
else:
chances -= 1
print("Too small")
real_answer = random.randint(1, 1000)
user_answer = int(input("This is a guessing game, please guess a number from 1 to 1000. You have 5 chances"))
Looper()
除了希望
chances
成为Looper
的参数(例如def looper(chances=5):
)之外,还可以在函数内部使用global chances
来获取外部变量的引用更好:
也有可能,但是是全局状态
完整故事:
相关问题 更多 >
编程相关推荐