问题描述
说明:创建一个程序,要求用户输入一系列数字.用户应该输入一个负数来表示系列结束.输入所有正数后,程序应显示它们的总和.
Instructions: Create a program that asks a user to enter a series of numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.
我使用的是 Python 2,Python IDLE
I am using Python 2, Python IDLE
我正在为此作业使用 while 循环.到目前为止,我制作了一个程序,当用户在 while 循环下输入一个正数时,收集该数字并继续添加它,直到用户输入一个负数.我试图找到一种方法将第一个用户输入包含到程序中.
I'm using a while loop for this assignment. So far, I made a program that is saying, while the user enters a positive number under the while loop, collect that number and keep adding it until the user enters a negative number. I am trying to find a way to include the first user input into the program.
print('This program calculates the sum of the numbers entered and ends
after inputting a negative number')
total = 0.00
number = float(input('Enter a number: '))
while number >= 0:
print('Enter another positive value if you wish to continue. Enter a
negative number to calculate the sum.')
number = float(input('Enter a number: '))
total = total + number
print('The sum is', total)
推荐答案
已将您的代码简化为以下内容.
在 while 循环中检查输入并在出现负值时退出.
Have reduced your code to the below.
Performs checking of input in while loop and exits upon negative value.
total = 0.00
while True:
print('Enter another positive value if you wish to continue. Enter a negative number to calculate the sum.')
number = float(input('Enter a number: '))
if number >= 0: # Check for positive numbers in loop
total += number
else:
break
print('The sum is', total)
这篇关于While 循环用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!