Python If / Else仅按顺序返回,而不是按逻辑返回

时间:2016-11-05 20:14:00

标签: python if-statement while-loop

分辨

当一个整数包含" 0"或" 4"输入后,此if语句仅返回语句中的第一个。

例如,在下面的代码中,如果我输入" 60",它将执行:

打印"很好,你不贪婪 - 你赢了!"出口(0)

不是

死了("你贪婪的混蛋!")

正如我所期望的那样,怎么样> = 50。

尝试了一系列更改,但似乎无法按预期执行。谁知道这里发生了什么?

def gold_room():
    print "This room is full of gold. How much do you take?"
    number_type = False

    while True:

        choice = raw_input("> ")

        how_much = int(choice)

        if "0" in choice or "4" in choice and how_much < 50:
            print "Nice, you're not greedy - you win!"
            exit(0)
        elif "0" in choice or "4" in choice and how_much >= 50:
            dead("You greedy bastard!")
        else:
            print "Man, learn to type a number. Put a 0 or a 4 in your number."

5 个答案:

答案 0 :(得分:2)

您有运营订单问题。 and运算符比or运算符绑定得更紧密,因此当您编写:

  if "0" in choice or "4" in choice and how_much < 50:

你实际上得到了:

  if ("0" in choice) or ("4" in choice and how_much < 50):

并希望,通过这些括号,显而易见的是,为什么进入60会触发&#34;尼斯,你不会贪婪 - 你赢了!&#34; message(因为它匹配"0" in choice coindition,并且因为该条件为真,所以整个or语句都为真。)

添加括号以获得所需内容:

  if ("0" in choice or "4" in choice) and how_much < 50:

有关详细信息,请参阅this article

答案 1 :(得分:1)

你的条件中需要一些括号,以确保按照你想要的方式进行评估,例如:

    if ("0" in choice or "4" in choice) and how_much < 50:

在下一个条件下你也需要类似的东西。

答案 2 :(得分:1)

您应该将条件分成逻辑组。此外,您重复了条件"0" in choice or "4" in choice,使用如下所示的优化结构:

if "0" in choice or "4" in choice:
    if how_much < 50:
        print "Nice, you're not greedy - you win!"
        exit(0)
    elif how_much >= 50:
        dead("You greedy bastard!")
else:
    print "Man, learn to type a number. Put a 0 or a 4 in your number."

答案 3 :(得分:0)

那是因为和在或之前执行 https://docs.python.org/3/reference/expressions.html#operator-precedence 在正确的位置的一些()将解决这个问题。

如果将测试分成不同的功能,那么测试它也会更容易

答案 4 :(得分:0)

Python会这样做: choice = '60' how_much = 60 如果选择中的“0”(将返回True)或选择中的“4”和how_much&lt; 50(这将返回false但是因为你这样做了或者它会继续它) 你应该这样做:

if ("0" in choice or "4" in choice) and how_much < 50:
        print "Nice, you're not greedy - you win!"
        exit(0)
elif how_much >= 50:
        dead("You greedy bastard!")

只有当它返回True时,parantheses才会这样做,然后比较看看变量“how_much”是否小于50。 之前,它正在检查“0”是否在选择中,或者如果选择中的4和how_much小于50. OR使得它只有一个语句必须为True才能继续下一行代码(AND使得“4选择和how_much&lt; 50”只返回真或假,必须与“0选择”进行比较)

很抱歉,如果它没有多大意义,但我困了 希望你明白了。

相关问题