0

I was trying to run this:

import sys

# Program 
print("Hallo",sys.argv[1])

But getting this error:

Traceback (most recent call last):
File "C:\Users\Shakh\Desktop\Hello3.py", line 4, in
print("Hallo",sys.argv[1])
IndexError: list index out of range

Nimantha
  • 6,405
  • 6
  • 28
  • 69

3 Answers3

2

Try this:

import sys
print("Hallo",sys.argv[0])

There is no index 1 at the time, list's index start with 0.

Anthony
  • 23
  • 6
1

sys.argv contains a list of command line arguments that you have supplied.

If you don't give any arguments (except for python program.py), the list will have only one argiment i.e., only sys.argv[0].

You will need to either give some argument like python program.py xyz, or use sys.argv[0]. Using sys.argv[0] will return the name of python file to you.

Skywalker
  • 582
  • 1
  • 5
  • 16
  • Can you explain how should I give some argument like (python program.py) . What you have written in your 3rd part 1st line . – Shakhawat Hossain Turag Jun 20 '18 at 06:01
  • If I wanted my program to say "Hello Vaibhav", then I would give the argument like python program.py Vaibhav. And my print statement will be print("Hello",sys.argv[1]) – Skywalker Jun 21 '18 at 06:33
0

sys.argv will hold command line arguments that you pass when you run the program. For example, you could run this as:

python Hello3.py Shakhawat
Thursdays Coming
  • 1,002
  • 13
  • 28