Search code examples
python-3.xfor-loopinputsum

How to get the sum of a user input in a for loop?


  1. step: I will let the user write how many numbers he/she can write.
  2. step: the user can write for example 2.
  3. step: the user write 2 and 4.
  4. step: the sum of step 3 have to be build (6).

Step 1 - 3 is clear, but can anyone help me how to build the sum in step 4?

x = int(input("How many numbers do you have?: "))

for i in range(x):

print(i+1,".number is")
y = int(input())

Solution

  • You have a sum variable that starts off as 0. Then in each iteration of the loop you just add y to sum_.

    sum_ = 0
    for _ in range(x):
      y = int(input("> "))
      sum_ += y
    print("Sum: ", sum_)
    

    You should also handle the case of non numeric characters being entered (catching the error)

    I used sum_ instead of sum since sum is a builtin function (which you should not just overwrite). Also, instead of i in the range loop, I discarded the index using an underscore (some IDE's would otherwise tell you that you are not using the variable)