-2

Here is the code.Please help me correct it.

#!/usr/bin/env python

import sys

def print5times(line_to_print):
        for count in range(0,5) :
                print line_to_print

print5times(sys.argv[1])

when running this code i am getting this error:

 Traceback (most recent call last):
   File "./func.py", line 9, in <module>
     print5times(sys.argv[1])
 IndexError: list index out of range
faust_
  • 17
  • 5
  • Do you understand what `sys.argv` is? – OneCricketeer Dec 03 '16 at 10:26
  • I am just starting out in programming. – faust_ Dec 03 '16 at 10:30
  • In Python, list indices start at 0, meaning the first element is `list[0]`, the second is `list[1]`, etc. – qxz Dec 03 '16 at 10:32
  • 1
    That's fine, but it's unclear if you following any specific guides, but if you were, it should explains that. Otherwise, it's not encouraged to just go running randomly code you find without reading and understanding the documentation for each piece you do not understand. And if you just started, it's recommended to to use Python3 – OneCricketeer Dec 03 '16 at 10:33
  • 1
    @qxz The first argument would be the script name here – Pierre Barre Dec 03 '16 at 10:33
  • @user312016 I was making a (slightly [un]related) comment in general about arrays, not specifically `sys.argv`. – qxz Dec 03 '16 at 10:36

2 Answers2

1

sys.argv[1] Gives you the second argument passed on the command line.

The IndexError comes from the fact you don't pass enough arguments to your script.

Even if you did that correctly, with your current snippet, you would print the argument 9 times instead of only 5, as your function name suggests.

qxz
  • 3,814
  • 1
  • 14
  • 29
Pierre Barre
  • 2,174
  • 1
  • 11
  • 23
0

Have a look at sys.argv[1] meaning in script

Now in your Python code, you can use this list of strings as input to your program. Since lists are indexed by zero-based integers, you can get the individual items using the list[0] syntax. For example, to get the script name:

script_name = sys.argv[0] # this will always work.

Although that's interesting to know, you rarely need to know your script name. To get the first argument after the script for a filename, you could do the following:

filename = sys.argv[1]

This is a very common usage, but note that it will fail with an IndexError if no argument was supplied.

Community
  • 1
  • 1
Gerrit Verhaar
  • 446
  • 4
  • 12