得到错误,但我不知道为什么......(我正在学习)我的代码;
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();
Run Code Online (Sandbox Code Playgroud)
错误; (一些剧本的作品)
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
Run Code Online (Sandbox Code Playgroud)
除了答案所说的内容之外,我建议你不要使用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
Run Code Online (Sandbox Code Playgroud)
另外,使用循环而不是if语句.否则,您将无法询问用户他/她是否想要无限期地继续.
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |