Skip to content
beginner

How to Accept Command-Line Arguments in Python

A script that only works when you edit the code every time is not yet a tool. It is a note to yourself. Command-line arguments turn that note into…

Published 2026-09-05Updated 2026-09-1210 min read
Vibrant urban street in Tokyo featuring a teal taxi, pedestrians, and local shops.
Vibrant urban street in Tokyo featuring a teal taxi, pedestrians, and local shops. Photo by Ayyeee Ayyeee on Pexels.

A script that only works when you edit the code every time is not yet a tool. It is a note to yourself. Command-line arguments turn that note into something you can run again and again with different inputs—no editing required.

Here is the beginner habit I see constantly: you write a script, hardcode a value inside it, run it, get the result, and then edit the file when you need a different result. That works for about ten minutes. Then you want to greet five different names, process three different files, or run the same calculation with new numbers, and suddenly you are the human input system for your own program.

Command-line arguments fix that. They are the values you type after the script name when you run it from the terminal. Instead of editing code, you type:

python greet.py Ada

and the script uses Ada without you touching the source file.

This tutorial assumes you already know how to run a Python file and how to import modules. If those feel shaky, go back and practice them first—they take five minutes, and everything here builds on them.

Why Your Script Should Accept Input at the Terminal

Let me show you the problem before the solution.

Imagine you wrote a small script that greets a user:

name = "Ada"
print(f"Hello, {name}!")

Run it, and you get:

Hello, Ada!

Now you want to greet Grace. What do you do? You open the file, change "Ada" to "Grace", save, and run again. That is the hardcoding habit. It works, but it does not scale. Every new input costs you an edit, and every edit is a chance to break something that was already working.

Command-line arguments change the relationship between you and your script. The script stops being a fixed recipe and becomes a machine with an input slot. You feed it different values at the terminal, and it produces different output without a single line of code changing.

That is how real command-line tools behave. When you run a program that processes a file, you do not edit the program to point at each new file. You pass the filename as an argument. This is the first step toward scripts that process files, clean data, or generate reports without code edits—the kind of practical automation that makes Python worth learning.

A Quick Look at the Raw Inputs: sys.argv

A left-to-right flow shows the terminal command `python show_args.py apple banana` entering Python and becoming a sys.argv list with `show_args.py` at index 0, `apple` at index 1, and `banana` at index 2; a note indicates that all values arrive as strings.
The terminal passes the script name and typed values to Python as a list of strings; real arguments begin at `sys.argv[1]`.

Before we build the proper tool, let me show you what Python does with the text you type after python. It collects everything into a list called sys.argv.

The name looks strange, but the mechanism is simple. When you run a Python script, the interpreter gathers everything you typed on the command line and stores it in a list. The first item, at index 0, is always the script name itself. The real arguments start at index 1.

Create a file called show_args.py with this content:

import sys

print(sys.argv)

Now run it with a few arguments:

python show_args.py apple banana cherry

You will see:

['show_args.py', 'apple', 'banana', 'cherry']

Python took everything after python, split it into separate strings, and handed you the whole list. The script name is at position 0. The arguments you actually care about are sys.argv[1:]—everything from index 1 onward.

One detail matters immediately: every argument arrives as a string, even if it looks like a number. If you run python add.py 10 20, Python does not hand you the integers 10 and 20. It hands you the strings "10" and "20". You have to convert them yourself if you want to do math.

sys.argv is a useful mental model. It shows you exactly what the terminal passes to your script. But for real scripts, you will usually want something with more structure.

Knowledge check

Check your understanding

Answer this question before you continue.

If you run `python show_args.py apple banana`, what list does `print(sys.argv)` display?
Output Prediction

Focus: Identify which entries in sys.argv contain the script name and the real command-line arguments.

```python
import sys
print(sys.argv)
```

Why argparse Beats Raw sys.argv for Real Scripts

Here is where sys.argv starts to hurt.

Suppose you build a script that takes a name and a number of repetitions. With sys.argv, you have to remember the order: name first, number second. Run it wrong, and the script either crashes or silently does the wrong thing. There is no help text. There is no validation. If the user forgets an argument, your script has to check len(sys.argv) and print its own error message.

That is a lot of manual work for a beginner, and it is exactly the kind of work that invites bugs.

The Python standard library includes a better tool: argparse. It is built in, so you do not need to install anything. It handles the parts of command-line parsing that you should not have to write yourself:

  • Named arguments, so users do not have to memorize positions
  • Automatic help text when someone runs your script with -h or --help
  • Built-in error messages when required values are missing
  • Type conversion, so a numeric argument can arrive as a number instead of a string

Here is a quick comparison to keep the two tools straight:

sys.argvargparse
What you getA raw list of stringsParsed values with names
Argument orderPosition mattersNamed, so order is flexible
Help textYou write it yourselfAutomatic with -h
Missing valuesYou check and handleBuilt-in error message
Type conversionYou convert manuallyDeclare the type once
Best forTiny scripts, quick experimentsReal tools you will reuse

My rule is simple: if the script is a quick experiment I will run once, sys.argv is fine. If the script is something I will run again next week, or hand to someone else, I use argparse. The setup cost is small, and the payoff starts the first time you forget what arguments your own script expects.

Knowledge check

Check your understanding

Answer this question before you continue.

Which situation best matches the article's recommendation to use argparse instead of raw sys.argv?
Single Choice

Focus: Choose argparse when a reusable script needs named arguments, help, validation, and declared type conversion.

Build Your First argparse Script

Let us build the greeting script properly. Create a file called greet.py:

import argparse

parser = argparse.ArgumentParser(description="Greet a user by name.")
parser.add_argument("name", help="The name to greet")
args = parser.parse_args()

print(f"Hello, {args.name}!")

Run it with a name:

python greet.py Ada

You will see:

Hello, Ada!

Now run it with a different name:

python greet.py Grace
Hello, Grace!

Same script. Same code. Different output, because the input comes from the terminal instead of the source file.

Here is what each line does:

  • parser = argparse.ArgumentParser(...) creates the parser object. The description is a short sentence about what your script does.
  • parser.add_argument("name", ...) declares that the script expects one argument called name. Because the argument name has no dashes in front of it, it is a positional argument—the user must type it in that position.
  • args = parser.parse_args() reads the command line, checks it against the rules you declared, and stores the results.
  • args.name is how you read the value. argparse turns the argument name into an attribute you can access with dot notation.

That last point is the real payoff. You declare an argument called name, and suddenly args.name holds whatever the user typed. No manual list indexing. No remembering that the name is at index 1.

Knowledge check

Check your understanding

Answer this question before you continue.

After `parser.add_argument("name", help="The name to greet")` and `args = parser.parse_args()`, which expression reads the value supplied for the name argument?
Single Choice

Focus: Use a positional argparse declaration and access its parsed value through the matching args attribute.

Require a Value and Show Help

The greeting script works, but it has a problem. What happens if someone runs it without a name?

python greet.py

Try it. You will see an error like this:

usage: greet.py [-h] name
greet.py: error: the following arguments are required: name

That error message came from argparse, not from code you wrote. The script refused to run because a required value was missing, and it told the user exactly what to fix. You did not write a single line of validation logic.

Now run the script with the help flag:

python greet.py -h

You will see:

usage: greet.py [-h] name

Greet a user by name.

positional arguments:
  name        The name to greet

options:
  -h, --help  show this help message and exit

That entire help screen is automatic. argparse generated it from the description you wrote and the help= text you attached to each argument. Anyone who runs your script with -h gets a clean summary of what the script does and what it expects.

This is the moment a script starts feeling like a real tool. It tells you what it needs, refuses to run with missing inputs, and explains itself on request. That is not extra ceremony. That is the difference between a script only you can run and a tool anyone can use.

Tip: Write the help= text for a future user who has never seen your code. That future user is often you, three weeks from now, with no memory of what the script expects.

Knowledge check

Check your understanding

Answer this question before you continue.

What happens when the greeting script is run as `python greet.py` without a name?
Misconception Check

Focus: Interpret argparse's behavior when a required positional argument is omitted.

Common Beginner Mistakes and How to Fix Them

These three mistakes show up constantly. They are normal. Each one teaches you something about how the mechanism works.

Mistake 1: Not reading the error message

When you run a script without a required argument, argparse prints a clear error. Beginners sometimes see the red text and assume the script is broken.

It is not broken. It is protecting you. The error message tells you exactly which argument is missing. Read it, add the argument, and run again. The error is the script doing its job.

Mistake 2: Assuming numbers arrive as numbers

Every command-line argument starts as a string. If your script needs a number, you have to tell argparse to convert it:

import argparse

parser = argparse.ArgumentParser(description="Double a number.")
parser.add_argument("number", type=int, help="The number to double")
args = parser.parse_args()

print(args.number * 2)

The type=int part tells argparse to convert the incoming string to an integer. Without it, args.number would be a string, and multiplying a string by 2 would give you "55" instead of 10 when you pass 5.

Mistake 3: Confusing the script name with the first real argument

With sys.argv, the script name lives at index 0. The first real argument is at index 1. Beginners frequently grab sys.argv[0] expecting their first input and get the filename instead.

The fix is the slice: sys.argv[1:] gives you everything after the script name. Or skip the problem entirely and use argparse, which handles that indexing detail for you.

Practice: Turn a Fixed Script into a Reusable One

Here is your task. Take this script with a hardcoded value and turn it into a script that accepts input from the command line:

city = "Paris"
print(f"Selected city: {city}")

Your goal: make it so you can run:

python select_city.py London

and get:

Selected city: London

The changes you need are small. Import argparse. Create a parser. Add an argument called city. Parse the arguments. Then use args.city instead of the hardcoded string.

When you are done, test these three things:

  1. Run it with a city name and confirm the output changes.
  2. Run it with a different city name and confirm the output changes again.
  3. Run it with -h and confirm you see a help screen describing the script.

If all three work, you have built your first reusable command-line tool. The code no longer cares which city you ask about. You decide at the terminal, every time, without editing a single line.

The next step is natural: use command-line arguments to feed your script a filename or data source. That is how you build scripts that process files, clean up data, or generate reports—the practical projects where Python really earns its keep. Start with this practice task, and you will be ready for them.

Knowledge check

Final check

Finish the article by checking the ideas you just learned.

Given the article's number-doubling script, what is printed when it is run with `python double.py 5`?
Question 1 of 2Output Prediction

Focus: Predict how argparse's type=int conversion changes a numeric command-line argument before multiplication.

```python
parser.add_argument("number", type=int, help="The number to double")
args = parser.parse_args()
print(args.number * 2)
```
A learner wants `python select_city.py London` to print `Selected city: London`, but the script still contains `city = "Paris"`. Which change is required to make the terminal value control the output?
Question 2 of 2Debugging

Focus: Diagnose the missing argparse step that prevents a script from using the city supplied at the terminal.

```python
city = "Paris"
print(f"Selected city: {city}")
```

References

  1. argparse — Parser for command-line options, arguments and ...docs.python.org
  2. sys | Python Standard Library – Real Pythonrealpython.com
8sources checked
8source domains
5searches run

Research updated Sep 5, 2026

Practical resource

Want a more structured Python path?

Use the Python Starter Pack to turn scattered tutorials into a focused practice path.

View the bundle
Coming soon

Python Starter Pack

A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.

$9
PDF BundleTopic PackPythonBeginner
  • 5 curated chapters
  • Enhanced PDF edition with bundle-only learning guidance
  • Offline-friendly format for focused review
  • Source article links for future online updates

Coming soon

Free Python bundle

Get the LearnPyFast Python Starter Bundle

A focused collection of beginner-friendly Python resources to help you move from setup to building practical projects.

You’ll receive the bundle by email. You can unsubscribe anytime.

No spam. You can unsubscribe anytime. See our Privacy policy.

Related sites

Continue beyond Python

Explore related Worldmonger sites when you want to move from Python basics into JavaScript or LLM application building.

JavaScript tutorialstutorial

LearnJSFast

Beginner-friendly JavaScript tutorials for practical web development and self-taught developers.

JavaScriptFrontendWeb development
Visit LearnJSFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related tutorials

Continue with nearby Python topics and beginner-friendly explanations.

Captivating view of a stormy sea under dark clouds, showcasing powerful ocean waves.
beginner
6 min read

Beginner Python Project Ideas

You finished the syntax tutorials. You know what a loop does, you can write a function, and you understand what a dictionary is for. Then you close the…

Read tutorial