【问题标题】:Python If/Else Only Returning In Order, Not By LogicPython If/Else 仅按顺序返回,而不是按逻辑返回
【发布时间】:2017-03-19 11:20:12
【问题描述】:

已解决

当输入一个包含“0”或“4”的整数时,这个if语句只返回语句中的第一个。

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

print "很好,你不贪心——你赢了!"退出(0)

不是

dead("你这个贪婪的混蛋!")

正如我所期望的那样,how_much >= 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."

【问题讨论】:

    标签: python if-statement while-loop


    【解决方案1】:

    Python 会这样做: 选择 = '60' 多少 = 60 如果选择中的“0”(将返回真)或选择中的“4”并且how_much

    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 时,它​​才会比较变量“how_much”是否小于 50。 之前,它正在检查“0”是否在选择中,或者如果选择中的 4 和 how_much 小于 50。OR 使得只有一个语句必须为 True 才能继续下一行代码(AND使得“4 inchoice and how_much

    对不起,如果这没有多大意义,但我困了 希望你明白了。

    【讨论】:

    • 谢谢,成功了!
    【解决方案2】:

    您应该将条件分成逻辑组。另外,你有重复条件"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】:

    您遇到了操作顺序问题。 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 会触发“很好,你不贪心 - 你赢了!”消息(因为它与"0" in choice 匹配,并且由于该条件为真,整个or 语句为真)。

    加括号得到你想要的:

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

    详情请见this article

    【讨论】:

    • 谢谢,这个解释很有帮助!
    【解决方案4】:

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

    如果您将测试拆分为不同的功能,测试也会更容易

    【讨论】:

      【解决方案5】:

      您需要在条件句中添加一些括号,以确保以您想要的方式评估它们,例如:

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

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

      【讨论】:

      • 谢谢,解决了!
      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 2011-12-06
      • 2017-07-27
      相关资源
      最近更新 更多