myint = []
我希望此串列中僅輸入一個整數,如果不是,則輸入無效,并將創建另一個代碼,顯示“{} 不是整數。再試一次。” 但我似乎不知道該怎么做,已經 3 小時了
while 1:
myint1 = input("Enter an integer: ")
myint2 = list(map(int, myint))
myint2.sort(reverse=True)
myint3 = myint2.isInteger()
if myint1 == "": >when press enter the code ends and show the sorted list
print(f"sorted list: {myint2}")
break
myint.append(myint1)
# Python
# List
# Input
# Invalid code
uj5u.com熱心網友回復:
您可以通過嘗試將輸入轉換為 int 來檢查用戶是否輸入了數字。然后,如果他們沒有輸入 int,您可以使用 try except 拋出錯誤訊息。見下文:
list = [] # create list
while True:
userInput = input("Enter a number: ") # user enters something
try:
number = int(userInput) # try to change the input to a number
list.append(number) # if successful then append it
except:
print("Thats not a number!") # if it doesnt work print
userInput = input("Enter a number: ") # and get them to re-enter
print(list)
uj5u.com熱心網友回復:
2
mylist = []
while True:
myinput = input("Enter an integer: ")
if myinput == "":
mylist.sort(reverse=True)
print(f"\nsorted list: {mylist}")
break
try:
number = int(myinput)
mylist.append(number)
except:
print(f"{myinput} is not an integer. Try again: ")
myinput = input("Enter an integer: ")
number = int(myinput)
mylist.append(number)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/377933.html
標籤:列表 python-2.7 输入 输出
