簡體   English   中英

確保要列出的多個用戶輸入是 while 循環 Python 3 中的整數

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

下面的代碼按預期工作。 我試圖確保輸入的所有數據都是整數。 非整數應該得到錯誤信息。 我的 while 循環適用於第一個輸入,其中詢問用戶要輸入的數字數量。 但是,它不會捕獲后續輸入的錯誤。

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")

您實際上不會在任何時候嘗試轉換為整數。 下面只保存字符串。

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)

如果您將userNum一個集合 - userNum = set() - 其中只能有唯一值。

您的主要錯誤是忘記了 int():

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

但是,如果輸入錯誤,整個程序仍然必須重新啟動,因此我建議在需要時使用 try&except。 你還傾向於:

1.在不需要時轉換變量
2.使用+str() ,這可能不是最好的習慣

這段代碼應該很簡單,自定義的 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)))

您沒有將后續輸入轉換為 int()。

你需要類似的東西

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

以下解決方案應該有效。 主要變化:

(1) 添加了明確的ValueError檢查,因為這是很好的做法。
(2) 添加了明確的continue ,因為這也是一個很好的做法。
(3) 合並else子句來創建try / except / else結構。
(4) 在數字輸入代碼的循環中添加了try / except
(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM