Python 代码没有按照我的想法去做

Python code not doing what I think it's supposed to

我已经编写了一些带有条件语句的代码,但我认为它不应该执行所发生的事情。

我多次尝试重写代码。

def main():
def enter():
  inputenter = input("Please enter a number. ")
  if inputenter in ("1", "2", "3", "4", "5"):
    getready()
  else:
    inputstartagain = input("Invalid Request") 
def getready():
  inputgetreadybrush = input("Did you brush your teeth? ")
  if inputgetreadybrush == "Yes" or "yes" or "y" or "Y":
    inputgetreadyshower = input("Did you shower? ")
    if inputgetreadyshower == "Yes" or "yes" or "y" or "Y":
      print("Your output is: I already got ready. ")
    elif inputgetreadyshower == "No" or "no" or "N" or "n":
      print("Your output is: Shower ")
    else:
      print("")
  elif inputgetreadybrush == "No" or "no" or "n" or "N":
    inputgetreadyshower1 = input("Did you shower? ")
    if inputgetreadyshower1 == "Yes" or "yes" or "Y" or "y":
      print("Your output is: Brush ")
    elif inputgetreadyshower1 == "No" or "no" or "n" or "N":
      print("Your output is: Brush and Shower ")
  else:
    print("")

main()

我预计(这些是 if 语句的答案)1,y,n 的输出为 "Your output is: Shower" 但实际输出为 "Your output is: I already got ready. " 所有内容。

不可能 orinputgetreadybrush == "Yes" or "yes" or "y" or "Y":

这样的条件

永远是真的。它被解释为 (inputgetreadybrush == "Yes") or "yes" or "y" or "Y":

如果答案不是肯定的,下一次测试,or 'yes' 将被计为正确。

最好写成:

inputgetreadybrush[0].lower() == 'y':

为什么你要写这么多字来写一个简单的yes/no答案?

如果您尝试只检查第一个字母,会更容易。在这种情况下,您将看到答案的第一个字母是“y”还是“n

例如,您的 getready() 函数将看起来更清晰,如果您将这样做:

def getready():
    inputgetreadybrush = input("Did you brush your teeth? ")

    if inputgetreadybrush.lower()[:1] == "y":
        inputgetreadyshower = input("Did you shower? ")

        if inputgetreadyshower.lower()[:1] == "y":
              print("Your output is: I already got ready. ")

        else:
              print("Your output is: Shower ")

    elif inputgetreadybrush.lower()[:1] == "n":
        inputgetreadyshower1 = input("Did you shower? ")

        if inputgetreadyshower1.lower()[:1] == "y":
          print("Your output is: Brush ")

        else:
          print("Your output is: Brush and Shower ")

    # In case you want to truck if anithing else was press:
    else:
        print(f"What do you mean {inputgetreadybrush.lower()}? I do not understand...")

在这种情况下,人类将更容易更快地知道那里发生了什么。并且会看起来更有游行精神:))

将所有条件更改为正确的语法:

if (inputgetreadybrush == "Yes") or (inputgetreadybrush == "yes") or (inputgetreadybrush == "y") or (inputgetreadybrush == "Y"):

这解决了你所有的问题。