简体   繁体   中英

IndexError: list index out of range

beginner in python, please take a look at the below code:

import sys
if __name__ == '__main__':

     n = int(sys.argv[1]) 
     i=1
     s=0
     while i<n:
            if (i % 3 == 0 and i % 5 == 0): 
                pass
            elif (i % 3 == 0): 
                s = s+i
            elif (i % 5 == 0):
                s = s+i 
            i=i+1
     print 'The sum is of all 3s and 5s till {}: {}'.format(n,s)

The error keeps coming out, I don't know how to solve it:

      2 import sys
      3 if __name__ == '__main__':
----> 4     n = int(sys.argv[1])
      5     i=1
      6     s=0

IndexError: list index out of range 

Thank you!

You need to send at least one argument when calling the program (call it like > euler_1.py 1000 ), since the arguments are stored in sys.argv[1:] .

You can avoid this need by setting a default when no argument is supplied:

n = int(sys.argv[1]) if len(sys.argv) > 1 else 1000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM