list index out of range in simple Python script

前端 未结 6 1689
余生分开走
余生分开走 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: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].

提交回复
热议问题