[英]Data validation for multiple user inputs with Python
I am creating a function for my python course that receives a list and returns the same list without the smallest number.我正在为我的 python 课程创建一个 function ,该课程接收一个列表并返回相同的列表,但没有最小的数字。 However, I wanted to extend the function to ask the user for inputs to create the list after performing some data validations on the inputs.
但是,我想扩展 function 以在对输入执行一些数据验证后询问用户输入以创建列表。
I was able to validate the first input.我能够验证第一个输入。 However, I got stuck at the second data validation as I need to guarantee that the program should accept only integers in the list and throw and prompt the user again for every wrong input something like while not (type(number) == int) which breaks as soon as the user input matches an int.
但是,我被困在第二次数据验证中,因为我需要保证程序应该只接受列表中的整数,并再次抛出并提示用户输入每个错误的输入,比如 while not (type(number) == int) 哪个一旦用户输入与 int 匹配,就会中断。
How should I do this?我该怎么做?
def smallest():
# This function asks the user for a list
# and returns the same list without the smallest number or numbers
list_range = 'Not a number'
list_created = []
while not (type(list_range) == int):
try:
list_range = int(input('Please enter the total number of elements for your list: '))
except:
print('Please provide a number!')
for number in range(1,list_range + 1):
try:
list_element = int(input('Please enter the value of the %d element: ' %number))
list_created.append(list_element)
except:
print('Please provide a number!')
smallest = min(list_created)
result = []
for num in list_created:
if num != smallest:
result.append(num)
return result
Thanks for the help in advance!我在这里先向您的帮助表示感谢!
You could use a while loop until an int
value is entered:您可以使用 while 循环,直到输入一个
int
值:
for number in range(1, list_range + 1):
while True:
list_element = input('Please enter the value of the %d element: ' % number)
try:
list_element = int(list_element)
list_created.append(list_element)
break
except ValueError:
print('Please provide a number!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.