我做了一些代码,它会滚动两个模具并询问用户多少次。之后,它将询问用户是否想再次播放。出于某种原因,它应该在它应该的时候打破其中一个while循环。
以下是代码:
import random
again = True
rolls = 0
while again == True:
rolls = float(raw_input("How many times would you like the dice to roll?"))
while rolls >= 1:
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print dice1 , dice2
rolls = rolls - 1
again = raw_input("Would you like to play again?")
if again == "Yes" or "Y" or "yes" or "y":
again = True
else:
again = False
你们中的任何人都可以帮助我
答案 0 :(得分:8)
问题在于这一行:
if again == "Yes" or "Y" or "yes" or "y":
评估为:
if (again == "Yes") or "Y" or "yes" or "y":
换句话说,它总是如此。你的意思是:
if again in ("Yes", "Y", "yes", "y"):
答案 1 :(得分:4)
if again == "Yes" or "Y" or "yes" or "y":
这不符合你的想法。评估为:
if (again == "Yes") or ("Y") or ("yes") or ("y"):
非空字符串逻辑True
,因此整个语句将始终为True
。您需要将again
与每个可能的值进行比较。
if again in ("Yes", "Y", "yes", "y"):
# or
if again == "Yes" or again == "Y" or again == "yes" or again == "y":
答案 2 :(得分:1)
该行
if again == "Yes" or "Y" or "yes" or "y":
错误,将始终返回True。要修复它,请将其更改为
if again == "Yes" or again == "Y" or again == "yes" or again == "y":
这种情况正在发生,因为非空字符串始终是真实的。由于您只是在第一个表达式中再次比较字符串,因此您只需检查字符串“Y”是否为空。由于该字符串是硬编码的,因此它始终为True
做起来也可能更整洁
#Uppercase the input and then check if user said yes
if again.upper() in ("YES","Y"):
do_the_thing()
答案 3 :(得分:1)
问题出在你的陈述中
if again == "yes" or "Y" or "yes" or "y"
python中的语句被评估为True,除非它们等于0或None,这是假的。
你必须这样做
if again == "Yes" or again == "Y" or again == "yes" etc.
这是因为or "Y" or "yes"
总是评估为True。
答案 4 :(得分:1)
下面的工作:
import random
again = True
rolls = 0
while again == True:
rolls = float(raw_input("How many times would you like the dice to roll?"))
while rolls >= 1:
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print dice1 , dice2
rolls = rolls - 1
again = raw_input("Would you like to play again?")
# It correct and more short
again = True if again in ("Yes", "Y", "yes", "y") else False