0

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!

5
  • 2
    How are you calling/running your python script? Commented Feb 2, 2017 at 21:24
  • 1
    I just use the command line in Canopy Commented Feb 2, 2017 at 21:26
  • 1
    You should be calling it like python script.py argument. Commented Feb 2, 2017 at 21:26
  • i can do that in terminal, but can i also do that in canopy? Commented Feb 2, 2017 at 21:28
  • @AlbertYu try this script import sys if __name__ == '__main__': print sys.argv and run python script.py 1. after this run python script.py 1 2 3 and you will understand how it works Commented Feb 2, 2017 at 21:30

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

but i only have one input argument here
sys.argv[0] is the name of the program, arguments start from index 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.