[英]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.