为什么这个Python if()测试总是解析为true?

时间:2014-03-30 00:22:42

标签: 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 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" or "y":始终会解析为true并且始终会打印行Oak: I see!...,即使我输入N也是如此。为什么这个if()测试总是解析为真?

4 个答案:

答案 0 :(得分:4)

由于您没有指定目标/问题是什么,让我猜一下:

if sure == "Y" or "y":

每次评估为True,因为“y”始终为真。

提示:   尝试评估以下内容:

if 'y': print 'test'

你想要的更有可能是:

if sure == "Y" or sure == "y":

答案 1 :(得分:0)

更改

if sure == "Y" or "y"

if sure == "Y" or sure == "y"

更好:

if sure in ["Y", "y"]

答案 2 :(得分:0)

你应该这样做if语句:

if sure == "Y" or sure == "y":

此外,代码缺少一小块。也就是说当一个人决定不接受他们刚刚选择的起动器时。你应该添加的是:

if sure == "N" or sure == "n":
    print starter + "not selected.\n"
    x = 0

答案 3 :(得分:0)

在if语句

如果确定==“Y”或“y”:

它只会返回true。要解决此问题,您必须执行此操作:

如果确定==“Y”或确定==“y”:

如果您在拒绝时需要回复,那么您应该做类似的事情

如果确定==“N”或确定==“n”:         打印“橡树:......”(无论你想要他说什么)