简体   繁体   English

IndexError:列表索引超出范围

[英]IndexError: list index out of range

beginner in python, please take a look at the below code: python初学者,请看下面的代码:

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:] . 由于参数存储在sys.argv[1:] ,因此在调用程序时,您至少需要发送一个参数(请像> euler_1.py 1000那样调用)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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