【问题标题】:Why does the following short script in Python disregard the condition in "if"?为什么 Python 中的以下简短脚本会忽略“if”中的条件?
【发布时间】:2012-04-20 09:36:23
【问题描述】:

我希望它在参数大于 10 时给出“甜甜圈数量:很多”,当参数是 count

#!/usr/bin/python2.6 -tt
import sys
def donuts(count):
  if count < 10:
    x = str(count)
  else:
    x = 'many'
  print 'Number of donuts: ' + x

def main():
  donuts(sys.argv[1])

if __name__ == "__main__":
  main()

【问题讨论】:

标签: python if-statement


【解决方案1】:

sys.argv 将只包含字符串,即使您提供整数作为参数,例如,如果您将其称为 python donuts.py 4,那么 sys.argv[1] 将是 '4',并且您将尝试比较 '4' &lt; 10 当你实际上想要4 &lt; 10

首先,尝试将sys.argv[1] 转换为int:

def main():
    donuts(int(sys.argv[1]))

您可能还想添加一些错误处理,以防未提供参数或它不是整数:

def main():
    try:
        donuts(int(sys.argv[1]))
    except IndexError:
        print 'Missing argument'
    except ValueError:
        print 'Invalid argument'

【讨论】:

  • 非常感谢您的回答!对于像我这样的新 python 用户来说,这很有启发性。
【解决方案2】:

count 是一个字符串。试试count = int(count)

【讨论】:

    【解决方案3】:

    尝试将count 参数转换为int 进行比较:

    if int (count) < 10:
      x = str (count)
    else:
      x = 'many'
    

    因为您正在为 count 参数传递一个字符串参数,所以比较失败。

    【讨论】:

      【解决方案4】:

      您不会将输入作为整数开头。

      变化:

      def main():
        donuts(sys.argv[1])
      

      到:

      def main():
        donuts(int(sys.argv[1]))
      

      但是,如果他们输入字符串或小数而不是数值,则会遇到问题。

      【讨论】:

        【解决方案5】:

        在将 count 与 10 进行比较之前,您应该将其转换为 int:

        #!/usr/bin/python2.6 -tt
        import sys
        def donuts(count):
            if int(count) < 10:
                x = count
            else:
                x = 'many'
            print 'Number of donuts: %s' % x
        
        def main():
            donuts(sys.argv[1])
        
        if __name__ == "__main__":
            main()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-02-22
          • 2019-03-05
          • 1970-01-01
          • 2021-10-20
          • 2022-07-14
          • 1970-01-01
          • 2011-04-12
          相关资源
          最近更新 更多