繁体   English   中英

我的while或循环掷骰子不起作用

[英]My while or loop in a dice roll is not working

这是我的代码

import random as r

Diceroll = "Y"
while Diceroll == "Y":
    Roll = r.randrange(1,7)
    print(Roll)
    Diceroll  = input("Would you like to roll again: Y/N")
    while (Diceroll != "Y") or (Diceroll != "N"):
        Diceroll = input("Please enter either Y or N")

print("Thank you for rolling with us")

第一次打印后,它无限循环地循环播放。 Would you like to roll again我确定解决方案是显而易见的,但我找不到它。

对于既不是Y也不Y N输入,您需要一个更受约束的条件:

while (Diceroll != "Y") and (Diceroll != "N"):
    ...

要么

while Diceroll not in ('Y', 'N'):
    ...

一个简单的解决方案是:

import random as r

Diceroll = "Y"
while Diceroll == "Y" and Diceroll != "N":
    Roll = r.randrange(1,7)
    print(Roll)
    Diceroll  = input("Would you like to roll again: Y/N")


print("Thank you for rolling with us")

以下是输出:

4
Would you like to roll again: Y/NY
3
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NY
4
Would you like to roll again: Y/NY
1
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NY
6
Would you like to roll again: Y/NN
Thank you for rolling with us

通过使用不正确的logical operator ,您的程序逻辑存在缺陷:

  • 逻辑AND运算符:如果两个操作数均为True,则返回True,如果至少一个为False,则返回False

  • 逻辑OR运算符:如果一个或两个操作数均为True,则返回True,如果两个均为False,则返回False

这就是为什么while (Diceroll != "Y") or (Diceroll != "N")在输入YN下返回True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM