检查用户输入是否为整数

时间:2012-12-10 00:04:53

标签: python list

我目前的代码:

mylist = [0] * 7     
for x in range(7):
        sales=-1
        while (sales<0):
            sales = float(input("Sales for day {0}:".format(x)))
            mylist[x] = sales

            if  sales < 0:
                print ("Sorry,invalid. Try again.")


 print (mylist)

best = max(mylist)
worst = min(mylist)
average = sum(mylist)/len(mylist)
total = sum(mylist)

print ("Your best day had", best, "in sales.")
print ("Your worst day had", worst, "in sales.")
print ("Your average daily sales were:", format(average,'.2f'))
print ("Your total sales were:", format(total, '.2f'))

当我运行它时,我得到了:第一个有效,我的问题是我第二次运行它

Sales for day 0: 5
Sales for day 1:4
Sales for day 2:6
Sales for day 3:7
Sales for day 4:8
Sales for day 5:2
Sales for day 6:3
[5.0, 4.0, 6.0, 7.0, 8.0, 2.0, 3.0]
Your best day had 8.0 in sales.
Your worst day had 2.0 in sales.
Your average daily sales were: 5.00
Your total sales were: 35.00



Sales for day 0: 5
Sales for day 1:4
Sales for day 2:3
Sales for day 3:-4
Sorry,invalid. Try again.
Sales for day 3:four
Traceback (most recent call last):
line 44, in <module>
sales = float(input("Sales for day {0}:".format(x)))
ValueError: could not convert string to float: 'four'

我如何重新编码,以便python也会重新提示用户输入另一个整数,如果他们决定说“4”而不是数字而感谢很多。

3 个答案:

答案 0 :(得分:4)

您可以使用try .. except。这是一个浮动或再次提示的函数:

def get_float(prompt):
    while True: 
        try:
            return float(input(prompt))
        except ValueError:
            print "invalid input, try again!"

答案 1 :(得分:0)

我建议做一些类似于answer所做的事情,这基本上归结为:
使用try..except

答案 2 :(得分:0)

使用功能:

def get_int():
   sales = input("Enter a number :")
   if type(sales) == int or type(sales) == long: # Python 3.x doesn't have long-type objects
      # code to do whatever with sales
   else:
      print("Invalid input. Try again.")
      get_int()

在您获得有效输入之前,它会一直调用它。