【问题标题】:why is my if else statement incorrect?为什么我的 if else 语句不正确?
【发布时间】:2016-08-10 10:35:25
【问题描述】:

我刚刚习惯了 python 中的 if else 语句,但我在尝试让我的工作时遇到了一些麻烦,到底发生了什么?

x = input("Enter your string")
while not set(x).issubset({'m', 'u', 'i'}):
    print("false")
    x = input("Enter your string")
else:
    print("Your String is " + x)
Question = int(input("Which rule would you like to apply? enter numbers 1-4: "))
if Question is 1:
    print("hello")
    '''issue arises in the else area below'''
else if Question is not 1:
        print("other")

【问题讨论】:

    标签: python if-statement input


    【解决方案1】:

    这一行

    else if Question is not 1:
    

    应该阅读

    elif Question is not 1:
    

    【讨论】:

      【解决方案2】:

      在 Python 中,您不会像在 C++ 中那样编写 else if。你把elif写成一个特殊的关键字。

      if Question is 1:
          print("hello")
      elif Question is not 1:
          print("other")
      

      【讨论】:

      • 你不应该使用is来比较数字。
      • @JBernardo,是的,但这并不是导致这个问题的问题
      • 另外elif 是多余的,如果你用它来重新检查你刚刚检查过的相同条件。
      【解决方案3】:

      if...else 语句的语法是 -

      if expression(A):
         //whatever 
      elif expression(B):
         //whatever 
      else:
        //whatever 
      

      【讨论】:

        【解决方案4】:

        我认为在这种情况下你应该写的是:

        if Question==1:
            print("hello")
        else:
            print("other")
        

        您不需要if 检查Question 是否不是1,因为这就是else 的意思:它上面的if 语句不匹配。

        另外,使用== 比较数字,而不是is。

        在您确实需要else if 的情况下,Python 关键字是elif。

        if Question==1:
            print("hello")
        elif Question==2:
            print("goodbye")
        else:
            print("other")
        

        【讨论】:

        • @joelgoldstick 实际上q is 1 检查q 是否与另一个int 相同的对象,其值为1,实际上它适用于1,但通常仍然是比较数字的错误方法。
        猜你喜欢
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 2016-07-05
        • 1970-01-01
        相关资源
        最近更新 更多