Python验证输入是否为int且大于0

时间:2015-10-13 20:50:23

标签: python

所以我需要让客户端再次输入变量,如果它不是整数或小于或等于0.我不能让它得到程序错误并结束它。

def enter_amount():


amount=input("Enter amount:")
while (not isinstance(amount, int)) or amount<=0:
    amount=input("The amount can't be negative, please try again:")
return amount

试过这个,它总是没有通过测试。如果您有任何想法,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

您需要将输入转换为整数,然后检查该值。由于用户可能输入垃圾,您必须通过捕获值异常来处理整数转换。

def get_amount():
    while True:
        amount = input("Enter amount: ")
        try:
            val = int(amount)
            if val >= 0:
                break
            else:
                print("Amount can't be negative, try again")
        except ValueError:
            print("Amount must be a number, try again")
    return val

答案 1 :(得分:0)

V = self.vertex(QF)
      s = V[0] - 100
      e = V[0] + 100
      while s != e:
          p = QFS(a,b,c,s)
          x = (p[0] + 100.0)/10.0
          y = ((p[1] + 100.0)*-1)/10.0
          canvas.create_line(x-1,y-1,x+1,y+1)
          s += .1

答案 2 :(得分:-1)

你不能在函数之外使用return!将代码包装在函数中,应该没问题。

def test():
    amount=input("Enter amount:")
    while (not isinstance(amount, int)) or amount<=0:
        amount=input("The amount can't be negative, please try again:")
    print(amount)
    return amount

test()