list index out of range in simple Python script

前端 未结 6 1732
余生分开走
余生分开走 2021-01-24 12:53

I just started learning Python and want to create a simple script that will read integer numbers from user input and print their sum.

The code that I wrote is

         


        
6条回答
  •  梦谈多话
    2021-01-24 13:26

    You can also avoid the loop altogether:

    inflow = '1 2 34 5'
    

    Then

    sum(map(int, inflow.split()))
    

    will give the expected value

    42
    

    EDIT:

    As you initialize your result with 1 and not 0, you can then also simply do:

    sum(map(int, input.split()), 1)
    

    My answer assumes that the input is always valid. If you want to catch invalid inputs, check Anton vBR's answer.

提交回复
热议问题