import random
def diceroll():
num_dice = random.randint(1,6)
print("You got " + str(num_dice) + "!")
diceroll()
def question():
response = input("You want to roll again?\n")
while response == "y":
diceroll()
response = input("You want to roll again?\n")
if response == "n":
print("Thank you for playing! :) ")
exit()
while "y" or "n" not in response:
response = input("Please answer with y or n!\n")
while response == "y":
diceroll()
response = input("You want to roll again?\n")
if response == "n":
print("Thank you for playing! :) ")
exit()
question()
有什么办法可以让这段代码变得更简单并具有相同的功能吗?我尝试了另一个版本而不使用类但是一旦我输入另一个字符,除了“y”或“n”代码结束。
import random
answer = "yes"
while answer in ["yes", "y"]:
roll = random.randint(1,6)
print("You rolled " + str(roll) + "!")
answer = input("Would you like to roll again?\n")
if answer in ["n", "no"]:
print("Thank you for playing!")
else :
print("Please answer with yes or no!")
answer = input("Would you like to roll again?\n")
答案 0 :(得分:0)
除了" y"之后输入任何内容后程序退出的原因或"是"是因为你所采取的是留在循环中的条件。你的程序假设"留在循环中#34;意味着"玩游戏",但当有人输入非法输入时,他们也应该留在循环中。退出的唯一原因是明确要求它,通过回答" n"或"不"。
因此:
import random
while answer not in ["no", "n"]:
roll = random.randint(1, 6)
print("You rolled " + str(roll) + "!")
answer = input("Would you like to roll again?\n")
if answer not in ["yes", "y", "no", "n"]:
print("Please answer with yes or no!")
answer = input("Would you like to roll again?\n")
print("Thank you for playing!")