CodeBlanks Logo Icon CodeBlanks

sys.argv

Learn command-line arguments with sys.argv.

sys.argv

sys.argv is a list holding command-line arguments. It is used by importing the sys module:

import sys
print(sys.argv)
# python script.py Ayşe 25
# ["script.py", "Ayşe", "25"]

sys.argv[0] is always the script name. Real arguments start at sys.argv[1]. Each argument is a string — convert if you need a number.

It is the way to read parameters given when the script starts.

argv and IndexError

If the user does not give enough arguments, accessing sys.argv[1] raises IndexError. So you must first check that the list has enough elements:

import sys
if len(sys.argv) > 1:
    name = sys.argv[1]
else:
    name = "misafir"
print(name)

This pattern — first a length check, then access — prevents IndexError. Providing a default value makes the script robust.

This check is standard in command-line scripts.

Practice Greet with sys.argv

Write import sys. Assign sys.argv[1] if len(sys.argv) > 1 else "misafir" to name. Then write print("Merhaba, " + name). The script runs with no arguments.

Starter code

main.py
# bring in the sys module
# take argument if present, else use misafir
# print the greeting

Sample solution

main.py
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "misafir"
print("Merhaba, " + name)

Expected output

Merhaba, misafir

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the sys.argv access

Question
import sys
name = sys.____[1]
Answer
import sys
name = sys.argv[1]

Explanation: sys.argv[1] is the first real argument.

2 What does sys.argv[0] contain?

  • An empty string
  • The first argument
  • The argument count
  • The script name Correct answer

Explanation: sys.argv[0] is always the name of the script being run.

3 Match sys.argv concepts

Term Meaning
sys.argv[0] Script name
sys.argv[1] First argument
len(sys.argv) Argument count
import sys Required import

All lessons in Beginner