簡體   English   中英

如何編寫一個程序,不斷從用戶那里獲取輸入,直到所有輸入的總和達到 200

[英]How to write a program that would keep taking inputs from the user until the sum of all the inputs reach 200

允許用戶輸入的數字是:10、20 和 50。如果輸入任何其他數字,則程序應將其聲明為無效。

我嘗試了以下方法,但似乎沒有成功:

count = 0
total = 0
print("Enter the values of amounts collected")

while True:
    new_number = input('> ')
    count = count + 1
    total = total + int(new_number)
    if total==200 :
        print("You have successfully collected 200")
        break
    if total>200:
        print("Amount collected exceeds 200")
        break

樣本輸入:

> 10
> 50
> 50
> 50
> 10
> 20
> 10

樣品 output:

You have successfully collected 200

樣本輸入:

> 190
...

樣品 output:

Invalid input

樣本輸入:

> 50
> 50
> 50
> 20
> 50

樣品 output:

Amount collected exceeds 200

你只需要嵌套的if條件

total = 0
print("Enter the values of amounts collected")
while total<200:               # Loop in until total < 200
new_number = int(input('> '))
if new_number in [10,20,50]:   # First check input number is in 10,20,50
    total = total + new_number # Then add sum to total

    if total == 200:           # If total = 200 break
        print("You have successfully collected 200")
        break

    elif total >200:           # If total > 200 break
        print("Amount collected exceeds 200")
        break
else:                         # If number not in 10,20,50 then print invalid input
    print("Invalid input")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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