Python代码没有做我认为应该做的事情

2024-09-29 19:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用条件语句写了一些代码,我不认为它应该做什么。你知道吗

我试过多次重写代码。你知道吗

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”为了一切。你知道吗


Tags: oryouinputoutputyourifisdef
3条回答

为什么你要写这么多单词来回答一个简单的是/否?

如果你只检查第一个字母会更容易。在这种情况下,您将看到答案的第一个字母是“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...")

在这种情况下,人类更容易更快地知道那里发生了什么。看起来更像游行队伍:))

不可能orinputgetreadybrush == "Yes" or "yes" or "y" or "Y":这样的条件

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

如果答案不是肯定的,下一个测试or 'yes'将被认为是真的。你知道吗

最好写为:

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

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

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

这解决了你所有的问题。你知道吗

相关问题 更多 >

    热门问题