# Dice Rolling Random Number and Guessing Game
import random
user_choice = 'y'
while user_choice != 'N' or user_choice != 'n':
print(random.randint(1,6))
user_choice = input("Do you want to continue: ")
print("You are exited")发布于 2021-11-28 09:22:24
while条件的逻辑错误。
您的循环将永远运行,因为字符将始终与建议的字符之一不同。因此,while条件始终为真,因为这两个部分中至少有一个始终为真。
你想要像这样的东西
while user_choice != 'N' and user_choice != 'n':
...如果你想采用更“pythonic”的方式,可以在while条件中查询一个集合:
while user_choice not in {'n', 'N'}:
....对于元组、列表,有许多类似的方法...表示条件,而不是单独查询“and”条件链中的每个字符。
发布于 2021-11-28 09:50:44
就编码而言,这个问题已经得到了回答,但我想更深入地解释为什么答案是and操作而不是or。
问题“用户是否既没有输入'n'也没有输入'N'__?”可以使用布尔代数表示为
'N'**)**,(**'n'** or Not)并使用DeMorgan定理,这可以重写为'n'**)和Not(**'N'**)在您的代码中,两种编写方法中的第一种将如下所示
while !(user_choice == 'N' or user_choice == 'n'):
我希望这能澄清你问题背后的逻辑。
https://stackoverflow.com/questions/70142027
复制相似问题