虽然循环用户输入?

时间:2019-10-18 03:53:36

标签: python python-2.7 python-requests

说明:创建一个程序,要求用户输入一系列数字。用户应输入一个负数来表示序列结束。输入所有正数后,程序应显示其总和。

我正在使用Python 2,Python IDLE

我正在使用while循环进行此分配。到目前为止,我编写了一个程序,说的是,当用户在while循环下输入一个正数时,请收集该数字并继续添加,直到用户输入一个负数为止。我正在尝试寻找一种方法,将第一个用户输入包括到程序中。

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)

2 个答案:

答案 0 :(得分:1)

已将您的代码简化为以下内容。
在while循环中执行输入检查,并在负值时退出。

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)

答案 1 :(得分:0)

我认为您是一个初学者,因此首先欢迎使用Python!我希望你玩得开心。现在,就您的代码而言,我注意到了两件事:

  1. 您可以简单地输入“如果希望继续输入另一个正值”。 输入一个负数以计算总和。”在您的输入中,为什么要打扰 有额外的打印说明?
  2. 您不必调用input()函数两次。

这是我的处理方式:

print('This program calculates the sum of the numbers entered and ends 
after inputting a negative number')
total = 0.00
while True:

   number = float(input("Enter a positive number(Negative number if you wish to terminate program"))
   if number >=0:
       total += number #equivalent to total=total + sum
   else:
       break # break out of while loop

print('The sum is', total)

P.S-为什么要使用Python 2 btw?