简体   繁体   English

如何编写一个程序,不断从用户那里获取输入,直到所有输入的总和达到 200

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

The numbers permissible for the user input are: 10, 20 and 50. If any other number is entered, then the program should declare it as invalid.允许用户输入的数字是:10、20 和 50。如果输入任何其他数字,则程序应将其声明为无效。

I've tried the following but it doesn't seem to work out:我尝试了以下方法,但似乎没有成功:

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

Sample input:样本输入:

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

Sample output:样品 output:

You have successfully collected 200

Sample input:样本输入:

> 190
...

Sample output:样品 output:

Invalid input

Sample input:样本输入:

> 50
> 50
> 50
> 20
> 50

Sample output:样品 output:

Amount collected exceeds 200

You just need nested if condition你只需要嵌套的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.

相关问题 接受用户的输入直到 5 个唯一输入 - Accept inputs from the user until 5 unique inputs "如何在函数中循环,并继续在 python 中输入" - How to loop in a function, and keep taking inputs in python 如何打印所有输入的总和? - how to print the sum of all the inputs? 如何在后台运行任务直到用户输入? - How to run a task in the background until user inputs? 在用户输入其他内容之前,如何在Python中进行无限循环? - How would I make an infinite loop in Python until a user inputs otherwise? 用户输入选择后如何重复程序 - How to repeat program after user inputs a choice 如何将用户输入写入 excel 文件? - How to write user inputs to an excel file? 编写一个程序,使用循环从用户那里获取 3 个键值输入,并使用这些键和值创建一个字典 - Write a program that uses a loop to take 3 key-value inputs from the user and create a dictionary using these keys and values Python:用户输入要写入/写入的文件名。 程序然后打开/读取 - Python: User inputs filename to write/be written to. program then opens/reads 从用户获取浮点输入,直到输入负数,然后计算总和、平均值、最大值和最小值,不包括负数 - Get floating point inputs from user until negative number is entered, then compute sum, average, max, and min, without including negative number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM