【问题标题】:Using “and” operator to compare two values使用“and”运算符比较两个值
【发布时间】:2021-01-20 23:29:17
【问题描述】:

对 python 非常陌生,并试图弄清楚如何使用 and 运算符来检查一个数字是否在 50 到 100 之间。尝试使用 and&& 和 || ,但只是得到无效的语法 python parser-16 错误。如果我从代码中取出 and 或替代项,那么它会部分工作并且不会给我一条错误消息,尽管它不会检查值是否低于 100,所以推测它必须我做错的部分?


x = int(input("Enter a number between 0 and 100"))

if x < 50:
    print("That is below 50!")
elif x > 50 and < 100:
    print("That is above 50!")
else:
    print("That number is too high!")

【问题讨论】:

  • 顺便说一句,x == 50 时你会做什么?另一方面,仅elif x &lt; 100: 就足够了(忽略x == 50 的情况)。

标签: python syntax operators


【解决方案1】:

关闭!


x = int(input("Enter a number between 0 and 100"))

if x < 50:
    print("That is below 50!")
elif x > 50 and x < 100:
    print("That is above 50!")
else:
    print("That number is too high!")

if x &gt; 50 and x &lt; 100 每次检查是否为真时都必须引用它

【讨论】:

    【解决方案2】:

    替代解决方案:

    x = int(input("Enter a number between 0 and 100: "))# for a better look
    
    if x < 50:
        print("That is below 50!")
    elif 100 >= x >= 50:# the numbers 50 and 100 shall be inclusive in one of the three params
        print("That is between 50 and 100!")
    else:
        print("That number is too high!")
    

    【讨论】:

      【解决方案3】:

      为了更简单,你可以写成如下。

      x = int(input("Enter a number between 0 and 100"))
      
      if x < 50:
          print("That is below 50!")
      elif 50 < x < 100:
          print("That is above 50!")
      else:
          print("That number is too high!")
      

      【讨论】:

      • 事实上,我相信这比x &gt; 50 and &lt; 100
      【解决方案4】:

      如果 x

        print('Below 50')
      

      elif x>50 和 x

        print('Between 50 and 100');
      

      其他:

        print('Above 100');
      

      试试这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 2012-11-03
        • 1970-01-01
        相关资源
        最近更新 更多