-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

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,764
  • 1
  • 13
  • 29
Pierre Barre
  • 2,128
  • 1
  • 10
  • 22
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
  • 414
  • 4
  • 9