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

前端 未结 5 1687
时光说笑
时光说笑 2021-01-16 08:49

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. I managed to gather the five numbers, but the

5条回答
  •  花落未央
    2021-01-16 09:00

    Gruszczy already solved your main problem, but here is some advice relevant to your code.

    First, it's easier to do a for loop rather than keep track of iterations in a 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:

    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:

    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:

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

提交回复
热议问题