简体   繁体   English

如何在Python中从用户输入中添加五个数字?

[英]How do I add five numbers from user input in Python?

As a practice exercise, I am trying to get five numbers from a user and return the sum of all five number using a while loop. 作为练习,我试图从用户那里获得五个数字,并使用while循环返回所有五个数字的和。 I managed to gather the five numbers, but the sum is not provided by my code (I get a number, but it is always double the last number). 我设法收集了五个数字,但是代码未提供总和(我得到了一个数字,但它始终是最后一个数字的两倍)。 I believe the issue is with my use of +=. 我相信问题出在我使用+ =。

x = 0   
while x < 5:
    x += 1
    s = (int(raw_input("Enter a number: ")))
    s += s
print s

Gruszczy already solved your main problem, but here is some advice relevant to your code. Gruszczy已经解决了您的主要问题,但是这里有一些与您的代码有关的建议。

First, it's easier to do a for loop rather than keep track of iterations in a while : 首先,它更容易做for循环,而不是保持跟踪迭代的while

s = 0
for i in range(5):
  s += int(raw_input('Enter a number: '))

Second, you can simplify it using the built-in sum function: 其次,您可以使用内置的sum函数来简化它:

s = sum(int(raw_input('Enter a number: ')) for i in range(5))

Third, both of the above will fail if the user enters invalid input. 第三,如果用户输入无效的输入,上述两种都会失败。 You should add a try block to take care of this: 您应该添加一个try块来解决此问题:

s = 0
for i in range(5):
  try:
      s += int(raw_input('Enter a number: '))
  except ValueError:
      print 'Invalid input. Counting as a zero.'

Or if you want to force 5 valid numbers: 或者,如果您想强制使用5个有效数字:

round = 0
s = 0
while round < 5:
  try:
      s += int(raw_input('Enter a number: '))
  except ValueError:
      print 'Invalid input.'
  else:
      round += 1

This should be better. 这样应该更好。

x = 0
s = 0   
while x < 5:
    x += 1
    s += (int(raw_input("Enter a number: ")))
print s

You were putting one of the results on to the sum of all results and lost the previous ones. 您将结果之一加到所有结果的总和上,却丢失了先前的结果。

Adding str or int by user_input & then printing the result - Adding 2 or more no's from users input 通过user_input添加str或int然后打印结果- 从用户输入中添加2个或更多no

example from the abv link 来自abv链接的示例

'''Two numeric inputs, explicit sum'''

x = int(input("Enter an integer: "))
y = int(input("Enter another integer: "))
sum = x+y
sentence = 'The sum of {} and {} is {}.'.format(x, y, sum)
print(sentence)
x = 0
s = 0   
    while x < 5:
        x += 1
        s += (int(raw_input("Enter a number: ")))
print s

you could do this also 你也可以这样做

print ("enter input number : ")

input1 = int(raw_input())

sum1 = 0

for y in range(0,input1+1):
       sum1 = sum1 + y
print ("the sum is " + str(sum1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM