繁体   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