关于python:检查用户输入是否为整数

Check if user input is an integer

我的当前代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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'))

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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也会重新提示用户输入另一个整数。


您可以使用try .. except。下面是一个函数,它再次获得一个浮点或提示:

1
2
3
4
5
6
def get_float(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print"invalid input, try again!"

使用函数:

1
2
3
4
5
6
7
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()

它将一直调用它,直到您得到一个有效的输入。


我建议做一些类似于这个答案中所做的事情,基本上可以归结为:
&使用try..except