简体   繁体   中英

How can is sum up an input range of numbers?

Dear stackoverflow community!

I just started learning python and want to figure out how to write following program:`

number = int(input('Enter ten numbers:'))
for i in range(1, 10):
  while True:
    try:
      number = int(input("Enter another number: "))
      break
    except:
      print("This is a string") 
for i in range(1, 10):
  res = 0
  res += int(input())
  print('The sum of these 10 numbers is:', res)

I want the user to input 10 numbers and during the process I want to check if the numbers are actually integers. So the number input works, it checks if its an integer, but then how can make this work at the same time? (To sum up the 10 integers that I got as input) :

for i in range(1, 10):
  res = 0
  res += int(input())
  print('The sum of these 10 numbers is:', res)

So basically i want two conditions for those 10 numbers that I got as Input.

Thanks for your help.

You are simply checking the user input, not storing it somewhere. Use this instead:

numbers = []
while len(numbers) != 10:
    try:
      numbers.append(int(input("Enter another number: ")))
    except ValueError:
      print("This is not an integer!") 

res = sum(numbers)
print('The sum of these 10 numbers is: {}'.format(res))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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