简体   繁体   English

确保要列出的多个用户输入是 while 循环 Python 3 中的整数

[英]Ensure multiple user inputs to list are integers within a while loop Python 3

the code below works as expected.下面的代码按预期工作。 I am trying to ensure that all data entered is integers.我试图确保输入的所有数据都是整数。 Non integers should get the error meessage.非整数应该得到错误信息。 My while loop works for the first input where the user is asked what # of numbers to enter.我的 while 循环适用于第一个输入,其中询问用户要输入的数字数量。 However it does not catch errors for the subsequent inputs.但是,它不会捕获后续输入的错误。

while True:
    try:
        userIn = int(input("Input no of numbers :"))     

        userNums = []
        uNums = []

        print("Type " + str(userIn) + " numbers in list :")          

        for index in range(int(userIn)):
            userNums.append(input("entry" + str(index+1) +" = "))

        for number in userNums:
            if number not in uNums:
                uNums.append(number)

        print("unique number counted")    
        for uNum in uNums:       
            print(str(uNum) + " count is " + str(userNums.count(uNum)) + "times")     
        break
    except:
        print("Error. only ints allowed")

You don't actually try and convert to integers at any point.您实际上不会在任何时候尝试转换为整数。 Below just saves the strings.下面只保存字符串。

for index in range(int(userIn)):
        userNums.append(input("entry" + str(index+1) +" = "))

And, by the way, you can get rid of the following:而且,顺便说一下,您可以摆脱以下内容:

for number in userNums:
    if number not in uNums:
        uNums.append(number)

If you made userNum a set - userNum = set() - which can only have unique values in it.如果您将userNum一个集合 - userNum = set() - 其中只能有唯一值。

Your main mistake is a forgotten int():您的主要错误是忘记了 int():

for index in range(userIn):
    num = int(input("entry" + str(index+1) +" = "))
    userNums.append(num)

However, still the whole program has to start again in case of a wrong input, therefore I recommend a try&except whenever in need.但是,如果输入错误,整个程序仍然必须重新启动,因此我建议在需要时使用 try&except。 You also tend to:你还倾向于:

1.convert variables when not necessary 1.在不需要时转换变量
2.use + and str() , which might be not the best habit 2.使用+str() ,这可能不是最好的习惯

This code should be straight forward and the customised INPUT-function might be useful in the future:)这段代码应该很简单,自定义的 INPUT 函数将来可能会有用:)

def INPUT(InputText):
    """customized input handling"""
    while True:
        try:
            return int(input(InputText))
        except ValueError:
            print ("Error: Only integers accepted")


#note: you could wrap the code below in a function 
#      and call the function afterwards if you want:

userIn = INPUT("Input no of numbers :")
userNums = []
uNums = []

print("Type {} numbers in list :".format(userIn))

for index in range(userIn):
    num = INPUT("entry {} = ".format(index+1))
    userNums.append(num)

for number in userNums:
    if number not in uNums:
        uNums.append(number)

print("unique number counted")

for uNum in uNums:
    print("{} count is {} times".format(uNum,userNums.count(uNum)))

You're not casting the subsequent inputs to int().您没有将后续输入转换为 int()。

You need something like你需要类似的东西

userNums.append(int(input("entry" + str(index+1) +" = ")))

The below solution should work.以下解决方案应该有效。 The main changes:主要变化:

(1) Added explicit ValueError checks, as this is good practice. (1) 添加了明确的ValueError检查,因为这是很好的做法。
(2) Added explicit continue , as this is also good practice. (2) 添加了明确的continue ,因为这也是一个很好的做法。
(3) Incorporated else clauses to create try / except / else structure. (3) 合并else子句来创建try / except / else结构。
(4) Added try / except to loop of number input code. (4) 在数字输入代码的循环中添加了try / except
(5) Use set to get unique items of list. (5) 使用set获取列表的唯一项。

while True:

    try:
        userIn = int(input("Input no of numbers :"))

    except ValueError:
        print("Error: only ints allowed")
        continue

    else:

        userNums = []

        print("Type " + str(userIn) + " numbers in list :")          

        for index in range(int(userIn)):
            while True:
                try:
                    x = int(input("entry" + str(index+1) +" = "))
                    userNums.append(x)
                    break
                except ValueError:
                    print("Error: only ints allowed")
                    continue

        uNums = set(userNums)

        print("Unique numbers counted:")

        for uNum in uNums:       
            print(str(uNum) + " count is " + str(userNums.count(uNum)) + " times")

        break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用while循环来保留用户输入到列表中的偶数个整数的计数? - Use a while loop to keep count of even integers that a user inputs into a list? 将 while 循环用户输入计算添加到列表中。 蟒蛇3 - Adding while loop user inputs calculations to a list. Python3 在python中的while-try循环中将不同的文本用户输入转换为整数 - Convert different text user inputs to integers in a while-try loop in python 如何创建一个 while 循环,将用户输入的整数添加到列表中,然后在每次输入失败后显示该用户输入列表? - How to create a while loop that adds user inputted integers into a list, then displays that list of user inputs after every failed input? 具有多个选项的 while 循环内的键盘输入 - Keyboard inputs within a while loop with multiple options 使用循环存储多个用户输入 - Storing Multiple User inputs while using a loop Python 3: Append 整数在带有 while True 循环的列表中 - Python 3: Append integers on a list with while True loop 在while true循环中无法识别Python用户定义的列表 - Python user defined list not being recognised within a while true loop Python 使用带有多个输入和选择的 while 循环 - Python using while loop with multiple inputs and choices 如何使用python中的循环(for和while循环)创建具有多个数据类型(字符和整数)的列表。 - How to create a list with multiple datatypes (characters as well as integers) using loop (both for and while loop) in python .
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM