【问题标题】:I want to do an input validation on an int(), but validate for str()我想对 int() 进行输入验证,但对 str() 进行验证
【发布时间】:2015-06-16 11:45:58
【问题描述】:

当用户的输入为

while True:

    try:
        x = input("how many times do you want to flip the coin?: ")
        if int(x) <= 0 or x.lower() == "stop": 
            break
        x = int(x)
        coinFlip(x)


     except ValueError:
        print ()
        print ("Please read the instructions carefully and try one more time! :)")
        print ()

我得到错误:

    if int(x) <= 0 or str(x).lower() == "stop":
ValueError: invalid literal for int() with base 10: 'stop'

【问题讨论】:

    标签: python validation debugging python-3.x optimization


    【解决方案1】:

    您会得到异常,因为评估的第一个条件是 int(x) &lt;= 0,此时 x 并不是真正的整数。

    你可以改变条件的顺序:

    if x.lower() == 'stop' or int(x) <=0
    

    这样您首先检查'stop',而不是评估int(x)(因为or 条件已经评估为True)。任何不是整数且不是'stop' 的字符串都会导致您已经在处理的ValueError 异常。

    【讨论】:

      【解决方案2】:

      您会得到一个ValueError,因为您无法将字符串'stop' 转换为整数。

      解决此问题的一种方法是使用帮助方法正确捕获ValueError,然后检查字符串是否为stop

      def should_stop(value):
          try:
              return int(value) <= 0
          except ValueError:
              return value.lower() == "stop"
      
      while True:
          x = input("how many times do you want to flip the coin?: ")
          if should_stop(x): 
              break
      

      【讨论】:

        猜你喜欢
        • 2021-07-18
        • 2021-09-02
        • 1970-01-01
        • 2013-02-20
        • 2017-03-19
        • 2018-09-29
        • 1970-01-01
        • 2019-12-09
        • 2017-08-10
        相关资源
        最近更新 更多