python - 我不明白为什么这个嵌套的while循环可以工作请python
问题描述
大家好,所以我开始制作一个掷骰子游戏,掷骰子然后显示值并询问用户是否想重新掷骰子。我知道如何做所有这些,但如果用户输入的值不是 Y(Yes) 或 N(No),我想放入一个循环的部分。所以我创建了另一个while语句来完成这个。如果您输入无效响应,程序会要求您输入 Y 或 N。然后,如果您再次输入无效响应,它会继续询问,直到输入预期值。这是代码,我将突出显示我不明白的部分。我评论了为什么我认为它有效,但我不确定。如果有人能解释它为什么起作用,我将不胜感激!
import random
value = random.randint(1, 2)
run = True
while run:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = input("Do you want to play again? (Y or N) \n")
if answer == "Y":
continue
if answer == "N":
print("Thanks for playing \n")
exit()
# after you type an invalid response it's stored in variable answer
# the program then goes to answer2 input which asks please enter Y or N
# if the program then detects an invalid answer it goes back to the top
# of the while statement and uses answer ones response which is still
# an invalid response???? I'm guessing since answer is always invalid and the
# decisions only two options that are yes or no it goes back to the top of the 2nd while loop
# Not sure tho.
# 2nd while loop
while answer != "Y" or "N":
answer2 = input("Please enter Y or N \n")
while answer2 == "Y":
print("You roll a six sided dice \n")
print("The dice landed on " + str(value) + "\n")
answer2 = input("Do you want to play again \n")
continue
if answer2 == "N":
print("THanks for playing")
exit()
我已经评论了为什么我认为它有效但是
解决方案
import random
value = random.randint(1, 2)
def getans():
while True:
answer = raw_input("Do you want to play again? (Y or N) \n")
if answer == "Y":
return True
elif answer == "N":
return False
else:
print ("Please enter Y or N \n")
continue
while True:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = getans()
if answer == True:
continue
elif answer == False:
print("Thanks for playing \n")
exit()
else:
print ("this will never run")
推荐阅读
- validation - 如何更改颤振的 pubspec.yaml 的模式验证?
- javascript - 无法在对象属性中访问 Mobx 对象
- javascript - 如何在柱形图中获取 xAxis 下方的数据标签
- maven-3 - Maven(pom.xml) 在部署/安装阶段不运行插件
- angularjs - 不能在指令模板中使用 ng-repeat
- node.js - 如何使用 sequelize 更改日期时间存储在 postgresql 中的格式?
- c - 创建 C“模板”函数
- javascript - Laravel @include 不会接受来自 JS innerHTML 的变量
- spring-boot - 在 Liquibase 上 Spring boot Support Fast 是否失败
- swift - 将 UIImage 导出为 Messages 应用的贴纸