【问题标题】:Inequalities/numerical values+conditional statements for python?python的不等式/数值+条件语句?
【发布时间】:2017-04-06 08:31:23
【问题描述】:

我想对python进行条件测试,检查给定输入数字的值是否等于或小于9,并且大于或等于0。

number =input( "Please enter a number! :" )
Please enter a number! :23
>>> edited_number=float(number)
>>> if edited_number >0 <9:
    print ("Entered value greater than or equal to 0 and less than or equal to 9!")

我收到一条打印的消息:

输入的值大于或等于 0 且小于或等于 9!

这显然是错误的,因为输入的值是 23。这向我表明

有没有办法让我有一个带有单个 if 的数字范围?还是每个 if 语句只解释一个条件?

PS:如果有任何相关性,我正在使用 Python 3.6.0b。

【问题讨论】:

    标签: python logic conditional


    【解决方案1】:

    你可以写

    if not (0 <= edited_number <= 9):
       print ("Entered value greater than or equal to 0 and less than or equal to 9!")
    

    【讨论】:

      【解决方案2】:

      那个链接的表达式并没有像你想象的那样做。你想要的是:

      0 <= edited_number <= 9
      

      或者,如果您对链式条件不满意,您可以使用详细形式:

      0 <= edited_number and edited_number <= 9
      

      表达式:

      edited_number > 0 < 9
      

      一样
      edited_number > 0 and 0 < 9
      

      edited_number 为 23 时,其计算结果为 True


      参考:

      Comparisons

      【讨论】:

      • 您建议的表达方式难道不是与想要的相反吗?
      • @ScottHunter 好眼光
      • @Moses Koledoyle;我可以和你澄清一下,你是说我的语法错误,而不是编码错误? :)
      • @apronedsamurai 我会说条件表达式没有正确编写 - 您的编码。变量应该在中间。如果您对链式条件不满意,最好使用详细形式。
      【解决方案3】:

      if edited_number &gt; 0 &lt; 9

      这在 python 中不起作用。 您需要像这样指定变量两次:

      if edited_number &gt; 0 and edited_number &lt; 9

      【讨论】:

        【解决方案4】:
        number =input( "Please enter a number! :" )
        
        edited_number=float(number)
        if  not (0 <= edited_number <= 9):
            print ("Entered value greater than or equal to 0 and less than or equal to 9!")
        

        输入:23

        输出:Entered value greater than or equal to 0 and less than or equal to 9!

        【讨论】:

          猜你喜欢
          • 2021-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-04
          • 2011-08-09
          • 2016-02-17
          • 1970-01-01
          相关资源
          最近更新 更多