list index out of range in simple Python script

前端 未结 6 1685
余生分开走
余生分开走 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(<iterable>) 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.

    0 讨论(0)
  • 2021-01-24 13:10

    for i in list gives the values of the list, not the index.

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

    If you wanted the index and not the value:

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

    And finally, if you wanted both:

    for index, value in enumerate(inflow):
    
    0 讨论(0)
  • 2021-01-24 13:21

    Considering: I just started learning Python

    I'd suggest something like this, which handle input errors:

    inflow = raw_input("Type numbers (e.g. '1 3 5') ") #in py3 input()
    #inflow = '1 2 34 5'
    
    try:
        nums = map(int, inflow.split())
        result = sum(nums)
        print(result)
    
    except ValueError:
        print("Not a valid input")
    
    0 讨论(0)
  • 2021-01-24 13:21

    If you were going to index the list object you would do:

    for i in range(len(inflow)):
        result += inflow[i]
    

    However, you are already mapping int and turning the map object into a list so thus you can just iterate over it and add up its elements:

    for i in inflow:
        result += i
    

    As to your second question, since you arent doing any type testing upon cast (i.e. what happens if a user supplies 3.14159; in that case int() on a str that represents a float throws a ValueError), you can wrap it all up like so:

    inflow = [int(x) for x in input().split(' ')] # input() returns `str` so just cast `int`
    result = 1
    for i in inflow:
        result += i
    print(result)
    

    To be safe and ensure inputs are valid, I'd add a function to test type casting before building the list with the aforementioned list comprehension:

    def typ(x):
        try:
            int(x)
            return True  # cast worked
        except ValueError:
            return False  # invalid cast
    
    inflow = [x for x in input().split(' ') in typ(x)] 
    result = 1
    for i in inflow:
        result += i
    print(result)
    

    So if a user supplies '1 2 3 4.5 5 6.3 7', inflow = [1, 2, 3, 5, 7].

    0 讨论(0)
  • 2021-01-24 13:25

    script that will read integer numbers from user input and print their sum.

    try this :

    inflow = list(map(int, input().split(" ")))
    result = 0
    for i in inflow:
        result += i
    print(result)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题