CLI arguments — Python Technical Interview Questions & Answers
CLI arguments
CLI arguments
- Command-line args come in sys.argv. argv[0] is the script name. argv[1:] are extra words after python file.py.
- Example: python add.py 2 3 → argv is [add.py, 2, 3]. int() them before adding. argparse is the nicer library for real tools.
- CLI arguments — output: script name then 5. argv[0] is the file; rest are extra words.
Technical Interview Tip: What is argv[0]? Then one tiny add.py idea.
Code Examples for CLI arguments
Example
# CLI arguments
import sys
print(sys.argv[0])
args = ["2", "3"] # like python add.py 2 3
print(int(args[0]) + int(args[1]))
CLI arguments — output: script name then 5. argv[0] is the file; rest are extra words.
How to Explain CLI arguments to an Interviewer
Explain CLI arguments as if you are teaching a junior — definition, then one tiny script.
Command-line args come in sys.argv. Example: python add.py 2 3 → argv is [add.py, 2, 3].
What does the example print, and why?
CLI arguments — output: script name then 5
What mistake do freshers make with CLI arguments?
CLI arguments — output: script name then 5.