[英]How to end a while loop and follow the other instructions if the number 0 is entered
我的代碼將所有用戶輸入的項目都放入一個列表中,我希望它在輸入0時停止,並遵循其他命令,例如對列表進行排序,刪除最高和最低值,然后查找它們的平均值。這就是代碼,遠:
i = 0
sizes = []
while i == 0:
size = int(input("Enter the weight of your parcel in grams, enter 0 when done: "))
sizes.append(size)
if size < 1:
break
sortedsizes = sorted(sizes)
largest = max(sizes)
smallest = min(sizes)
sizes.remove(largest)
sizes.remove(smallest)
print(sizes)
你不需要i
,你不想要的軟件包,體重少0。你可能要考慮使用float
,而不是int
-我住的地方,我們衡量kg
的包裹或g
信件-無論將采取包括部分(1.235千克或5.28克)。
如果有人輸入"22kg"
任何數字轉換都會崩潰-您應注意以下"22kg"
:
sizes = []
while True:
try:
size = int(input("Enter the weight of your parcel in grams, enter 0 when done: "))
if size > 0:
sizes.append(size)
elif size == 0:
break
else:
raise ValueError() # negative weight
except ValueError:
print("Only positive numbers or 0 to quit. Do not input text or kg/g/mg.")
sortedsizes = sorted(sizes) # you do nothing with this - why sort at all?
largest = max(sizes)
smallest = min(sizes)
sizes.remove(largest)
sizes.remove(smallest)
print(sizes) # this prints the unsorted list that got min/max removed...
輸出:
Enter the weight of your parcel in grams, enter 0 when done: 4
Enter the weight of your parcel in grams, enter 0 when done: 3
Enter the weight of your parcel in grams, enter 0 when done: 5
Enter the weight of your parcel in grams, enter 0 when done: 6
Enter the weight of your parcel in grams, enter 0 when done: -1
Only positive numbers or 0 to quit. Do not input text or kg/g/mg.
Enter the weight of your parcel in grams, enter 0 when done: DONE
Only positive numbers or 0 to quit. Do not input text or kg/g/mg.
Enter the weight of your parcel in grams, enter 0 when done: 2
Enter the weight of your parcel in grams, enter 0 when done: 0
[4, 3, 5] # this is the unsorted list that got min/max removed...
如果您只想從排序列表中刪除1個最大值和1個最小值,則可以簡單地將其刪除:
sortedsizes = sorted(sizes)
maxval = sortedsizes.pop() # remove last one from sortedsizes (== max)
minval = sortedsizes.pop(0) # remove first one from sortedsizes (== min)
print(sortedsizes) # print the sorted values
Doku:
如果要在輸入0時停止代碼(將大小附加到列表中並在重復過程之后繼續執行命令),則必須執行相反的操作。
while True:
size = int(input("Enter the weight of your parcel in grams, enter 0 when done: "))
sizes.append(size)
if size < 1:
break
當語句為false時,代碼從sortedsizes = sorted(sizes)
命令繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.