遇到错误,但我不知道为什么。(我正在学习)我的代码;
import random
input("Hit enter to roll the dice")
global answer
def rollDice():
result = random.randrange(1,6)
print ("It landed on.." + str(result))
answer = input("would you like to play again? [y/n]")
rollDice();
if (answer == "y" or "Y"):
rollDice();
错误; (某些脚本有效)
Hit enter to roll the dice
It landed on..5
would you like to play again? [y/n]y
Traceback (most recent call last):
File "diceRoller.py", line 11, in <module>
while (answer == "y" or "Y"):
NameError: name 'answer' is not defined
除了给出答案以外,我建议您不要使用global
,而应return
该人是否要继续,并根据该继续,例如:
import random
input("Hit enter to roll the dice")
def rollDice():
result = random.randrange(1,6)
print("It landed on.. " + str(result))
answer = input("Would you like to play again? [y/n]")
if answer in ("y", "Y"):
return True
return False
while rollDice():
continue
另外,请使用循环而不是if
语句。 否则,您将无法询问用户是否要无限期继续。
您的函数定义是需要知道answer
是全局的东西。 因此,将您的global
声明放入定义主体中。
def rollDice():
global answer
result = random.randrange(1,6)
print ("It landed on.." + str(result))
answer = input("would you like to play again? [y/n]")
也
if (answer == "y" or "Y"):
应该
if answer in ('y', 'Y'):
否则,您要检查的是(answer=="y")
还是("Y")
,后者始终为True
。
如果你想保持无限滚动,只要用户的答案肯定,那么你if
应该是一个while
。
while answer in ('y', 'Y'):
global
关键字必须在函数体内。 另外,就像Falmarri所说的那样, if (answer=="y" or "Y")
需要为'if answer ==“ y”或answer ==“ Y”
首先, global answer
在全局范围内无效。 将其放在函数中。
但是调试代码非常困难,因为回溯是指未显示在源代码中的一行代码! ( while
vs if
)
无论如何, if answer = 'y' or 'Y'
应该是if answer in tuple('yY')