如何验证用户输入以仅采用数字

时间:2016-09-25 13:08:39

标签: python python-3.x

我有两个问题:

  1. 如何显示从用户输入接受5个数字的最大和最小数字

  2. 如何验证用户输入以仅采用数字。

  3. 这是我的代码:

    input_set = list()
    num = input("Enter how many elements you want:")
    print("Enter numbers in array:")
    for i in range(int(num)):
        n = int(input("input number :"))
        input_set.append(int(n))
    print ("ARRAY: ", input_set)
    largest = input_set[0]
    for i in range(len(input_set)):
    
        if input_set[i] > largest:
            greatest = input_set[i]
    
    print("Largest number is :", greatest)
    
    smallest = input_set[0]
    for i in range(len(input_set)):
    
        if input_set[i] < largest:
            smallest = input_set[i]
    
    print("Smallest number is :", smallest)
    

2 个答案:

答案 0 :(得分:1)

以下是我修改上述代码的方法。这完成了两件事,确保输入是数字形式,并清理查找数组中的最大/最小数字。当然,如果用户没有输入数字,它将无限循环,但你总是可以为每个循环添加最大尝试次数(我将其留作读者练习)。

编辑: 纠正了一个错误......

input_set = list()
num = None
while num is None:
    ret = input("Enter how many elements you want:")
    try:
        num = int(ret)
    except ValueError:
        print ("Invalid input, please enter a digit.")

print("Enter numbers in array:")
for i in range(num):
    n = None
    while n is None:
        ret = input("input number :")
        try:
            n = int(ret)
            input_set.append(n)
        except ValueError:
            print ("Invalid input, please enter a digit.")

print ("ARRAY: ", input_set)
print ("Largest number is :", max(input_set))
print ("Smallest number is :", min(input_set))

答案 1 :(得分:1)

这个输入直到用户输入有效输入

input_set = list()
num = input("Enter how many elements you want:")
print("Enter numbers in array:")
for i in range(int(num)):
    while True:
        try:
            n = int(input())
        except ValueError:
            print("Enter a number")
            continue
        else:
            break
    input_set.append(int(n))
print ("ARRAY: ", input_set)
largest = input_set[0]
for i in range(len(input_set)):

    if input_set[i] > largest:
        print('greatest '+str(largest))
        print('current '+str(input_set[i]))
        largest = input_set[i]

print("Largest number is :", largest)

smallest = input_set[0]
for i in range(len(input_set)):

    if input_set[i] < largest:
        smallest = input_set[i]

print("Smallest number is :", smallest)