![](/img/trans.png)
[英]Python: for loop between if-else, how/why does this work?
[英]why the if-else does not loop
我發現我的編的if-else沒有循環,為什么會發生這種情況,如何修復它進行檢查?
我的編認為存儲用戶的輸入必須在10到100之間,然后刪除重復的輸入。 示例: num=[11,11,22,33,44,55,66,77,88,99]
結果:`[22,33,44,55,66,77,88,99]
inList=[]
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
if num >= 10 and num <= 100:
inList.append(num)
else:
num = int(input("Please enter a valid number: "))
print(inList)
我發現if-else僅執行一次,因此當我第二次輸入無效num時,編仍將我帶入下一個輸入過程。 會發生什么?
Please enter number 1 [10 - 100]: 1
Please enter a valid number: 1
Please enter number 2 [10 - 100]:
另外,請問如何檢查inList中是否有重復的num,然后刪除列表中的兩個num?
我還建議使用while循環。 但是,僅當第一個提示錯誤時才應進入while循環:
考慮以下示例:
inList = []
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
while not (num >= 10 and num <= 100):
num = int(input("Please enter a valid number [10 - 100]: "))
inList.append(num)
print(inList)
但是,我是否可以提出其他建議:
此代碼創建有效輸入列表[“ 10”,“ 11” ....“ 100”],如果默認情況下為字符串的輸入不在該列表內,則我們要求新輸入。 最后,我們返回該字符串的int值。 這樣,我們確保鍵入“ ashashah”不會引發錯誤。 試試看:
inList = []
valid = list(map(str,range(10,101)))
for x in range(1,11):
num = input("Please enter number {} [10 - 100]: ".format(x))
while num not in valid:
num = input("Please enter a valid number [10 - 100]: ")
inList.append(int(num))
print(inList)
我不是python專家,也沒有環境設置可以對此進行測試,但是我可以看到您問題的出處。
基本上,在您的for循環中,您說的是
if num is valid then
add to array
else
prompt user for num
end loop
第二個提示沒有任何反應,只是提示>結束循環。 您需要在for循環中使用另一個循環來獲取num並確保其有效。 以下代碼是應該起作用的工具,但如上所述,它不是專家,也不是測試環境,因此可能存在語法錯誤。
for x in range(1,11):
i = int(0)
num = int(0)
while num < 10 or num > 100:
if i == 0:
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
else:
num = int(input("Please enter a valid number: "))
i += 1
inList.append(num)
print(inList)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.