list index out of range in simple Python script

前端 未结 6 1741
余生分开走
余生分开走 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:02

    What your code is doing, in chronological order, is this:

    1. Gather user input, split per space and convert to integer, and lastly store in inflow
    2. Initialize result to 1
    3. Iterate over every item in inflow and set item to i
    4. Add the current item, i to result and continue
    5. After loop is done, print the result total.

    The broken logic would be at step 4.

    To answer your question, the problem is that you're not gathering the index from the list as expected-- you're iterating over each value in the list opposed to the index, so it's really undefined behavior based on what the user inputs. Though of course, it isn't what you want.

    What you'd want to do is:

    inflow = list(map(int, input().split(" ")))
    result = 1
    for i in range(len(inflow)):
        result += inflow[i]
    print(result)
    

    And on your last regard; there are two real ways to do it, one being the way you're doing right now using list, map and:

    inflow = [int(v) for v in input().split()]
    

    IMO the latter looks better. Also a suggestion; you could call stdlib function sum() over a list of integers or floats and it'll add each number and return the summation, which would appear more clean over a for loop.

    Note: if you're splitting per whitespace you can just call the str.split() function without any parameters, as it'll split at every whitespace regardless.

    >>> "hello world!".split()
    ['hello', 'world!']
    

    Note: also if you want extra verification you could add a bit more logic to the list comprehension:

    inflow = [int(v) for v in input().split() if v.isdigit()]
    

    Which checks whether the user inputted valid data, and if not, skip past the data and check the following.

提交回复
热议问题