list index out of range in simple Python script

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

    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")
    

提交回复
热议问题