下面的代码在我执行它时显示错误,是不是我在执行 Looper() 之前在第二行做了分配?但是,当我将机会 = 5 添加到 Looper() 的第一行时,它会起作用
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
(eg def looper(chances=5):
)的参数这一点之外,您还可以global chances
在函数内部使用来获取对外部变量的引用。
更好的:
def looper(chances=5):
if chances != 0:
...
也可能,但全局状态
CHANCES = 5
def looper():
global CHANCES
if CHANCES != 0:
...
完整故事:
import random
def looper(real_answer, chances=5):
for _ in range(chances):
user_answer = int(input("This is a guessing game, please guess a number from 1 to 1000. You have %i chances" % (chances, )))
if real_answer == user_answer:
return True
elif real_answer < user_answer:
print("Too large")
else:
print("Too small")
if __name__ == '__main__':
real_answer = random.randint(1, 1000)
if looper(real_answer):
print("Gotcha")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句