为什么这个Python if()测试总是解析为true?
我在做我的口袋妖怪:火红色文本冒险时遇到了一个问题。代码是相当基本的,但是我不知道为什么它不工作。 我才刚开始学编程,所以我不是专家。这是密码:3为什么这个Python if()测试总是解析为true?,python,Python,我在做我的口袋妖怪:火红色文本冒险时遇到了一个问题。代码是相当基本的,但是我不知道为什么它不工作。 我才刚开始学编程,所以我不是专家。这是密码:3 startertitle1 = "The GRASS TYPE Pokemon" startertitle2 = "The FIRE TYPE Pokemon" startertitle3 = "The WATER TYPE Pokemon" x = 0 while x == 0: print "*** There are three POK
startertitle1 = "The GRASS TYPE Pokemon"
startertitle2 = "The FIRE TYPE Pokemon"
startertitle3 = "The WATER TYPE Pokemon"
x = 0
while x == 0:
print "*** There are three POKEBALLS infront of you, which POKEBALL do you want? Pokeball (1), (2), or (3)"
pokeball = raw_input(">>>")
if pokeball == "1":
starter = "BULBASAUR"
startertitle = startertitle1
print "Are you sure you want to go with "+starter+", "+startertitle+"?[Y/N]"
elif pokeball == "2":
starter = "CHARMANDER"
startertitle = startertitle2
print "Are you sure you want to go with "+starter+", "+startertitle+"?[Y/N]"
elif pokeball == "3":
starter = "SQUIRTLE"
startertitle = startertitle3
print "Are you sure you want to go with "+starter+", "+startertitle+"?[Y/N]"
sure = raw_input(">>>")
if sure == "Y" or "y":
print "Oak: I see! "+starter+" is your choice! This Pokemon is really quite energetic!"
x = x+1
提前感谢您的帮助:)
问题描述:
当代码运行测试时,
if sure==“Y”或“Y”:
始终解析为true
,行Oak:I明白了代码>始终打印,即使我输入N
。为什么这个if()
测试总是解析为true?既然您没有指定目标/问题是什么,让我猜猜:
if sure == "Y" or "y":
每次的计算结果都为True,因为“y”始终为True
提示:
尝试评估以下各项:
if 'y': print 'test'
更可能您想要的是:
if sure == "Y" or sure == "y":
改变
到
更好的是:
if sure in ["Y", "y"]
您应做出如下if声明:
if sure == "Y" or sure == "y":
此外,代码缺少一小段。也就是说,当一个人决定不参加他们刚刚选择的首发。你应该补充的是:
if sure == "N" or sure == "n":
print starter + "not selected.\n"
x = 0
在if语句中
如果确定==“Y”或“Y”:
它只会返回真值。要解决此问题,必须执行以下操作:
如果sure==“Y”或sure==“Y”:
如果你想在说“不”时得到回应,你也应该做类似的事情
如果肯定==“N”或肯定==“N”:
打印“Oak:…”(你想让他说什么就说什么)如果我们要帮助你,你必须告诉我们什么不起作用。没有人会运行你的代码并试图猜测你打算做什么。哦,对了,对不起。基本上,在程序询问您是否确定后。即使sure==“N”,它也会打印代码的“sure==“Y”部分。(打印“Oak:我明白了!…”)我不确定我是否解释得很好/谢谢,但有人能告诉我为什么sure==“Y”或“Y”不起作用吗?那么你原来的if
表达式,if(双关语,无意中)括号将是if((sure==“Y”)或(“Y”)
。就在那里。您的语句被解读为if(sure==“Y”)或('Y')
。如果或
两侧的表达式为真,则整个表达式为真。现在还不清楚Python将如何评估表达式'y'
的真实性,因此您需要知道Python的规则规定除空字符串以外的任何字符串的计算结果都是true
。空字符串的计算结果为false
。
if sure == "Y" or sure == "y":
if sure == "N" or sure == "n":
print starter + "not selected.\n"
x = 0