Concepts / Writing Command-Line Programs

Writing Command-Line Programs

However, I strongly recommend that you stick to writing a maximum of a single logical line on each single physical line . The idea is that you should never use the semicolon. In fact, I have never used or even seen a semicolon in a Python program.

  • Programming

What Command-Line Arguments Are

When you run a program from the terminal or command prompt, you can pass information to it directly on the command line. For example, if you type python my_program.py hello world, you are running my_program.py and passing hello and world as arguments to that program. Command-line arguments let your program receive input without requiring the user to type responses interactively after the program starts. This is especially useful for scripts that process files, configure behavior, or chain together with other programs.

Python automatically collects all command-line arguments and stores them in a special variable called sys.argv, which is a list of strings. Your program can read and use these arguments to control its behavior.

Accessing Arguments with sys.argv

The sys.argv variable is a list of strings that contains the command-line arguments passed to your program. The first element, sys.argv[0], is always the name of the script itself. The remaining elements, sys.argv[1], sys.argv[2], and so on, are the arguments you typed after the program name. For instance, if you run python greet.py Alice Bob, then sys.argv[0] is 'greet.py', sys.argv[1] is 'Alice', and sys.argv[2] is 'Bob'. To use sys.argv in your program, you must first import the sys module at the top of your file.

A Simple Greeting Program

Write a program that accepts a name as a command-line argument and prints a personalized greeting.

Import the sys module: At the top of your program, write import sys so you can access sys.argv.

Check the number of arguments: Use len(sys.argv) to determine how many arguments were passed. If the user provided a name, len(sys.argv) will be 2 (the script name plus one argument).

Extract and use the argument: Access sys.argv[1] to get the name the user provided, then print a greeting that includes that name.

Run from the command line: Execute the program by typing python greet.py Alice at the command prompt. The program receives 'Alice' as sys.argv[1] and prints the greeting.

When you run python greet.py Alice, the program outputs: Hello, Alice! Welcome to our program.

Single Logical Line Per Physical Line

Python allows you to write multiple logical statements on a single physical line by separating them with semicolons. However, this practice is strongly discouraged. The recommended convention is to write a maximum of one logical line on each physical line of code. A logical line is a complete Python statement, such as an assignment, a function call, or a control structure. A physical line is what you see on your screen—each line that ends when you press Enter. By keeping one logical line per physical line, your code becomes much easier to read, debug, and maintain. In fact, experienced Python programmers rarely use semicolons in their code at all.

x = 5; y = 10; z =x + yThree logical lineson one physical linex = 5y = 10z = x + yOne logical line perphysical line
What does the difference between logical and physical lines look like in practice, and why does avoiding semicolons matter?

Always write one logical line per physical line. Never use semicolons to combine multiple statements on a single line. This makes your code clearer, easier to step through with a debugger, and simpler for other programmers (and your future self) to understand at a glance.

Common Mistakes When Writing Command-Line Programs

  • Forgetting to import sys before using sys.argv

    Python will raise a NameError because sys is not defined in your program's namespace.

    Fix: Always include import sys at the beginning of any program that accesses command-line arguments.

  • Assuming sys.argv[1] exists without checking the argument count

    If the user runs the program without arguments, sys.argv will only contain the script name, and accessing sys.argv[1] will raise an IndexError.

    Fix: Check len(sys.argv) before accessing specific indices, or use a try-except block to handle missing arguments gracefully.

  • Using semicolons to put multiple statements on one line

    While Python allows this, it violates the single logical line per physical line convention and makes code harder to read and debug.

    Fix: Write each statement on a separate physical line without semicolons.

  • Forgetting that sys.argv contains strings, not other data types

    sys.argv[1] and sys.argv[2] are the strings '5' and '10', so adding them produces '510', not 15.

    Fix: Convert command-line arguments to the appropriate type using int(), float(), or other conversion functions before performing operations on them.

Writing a Complete Command-Line Program

Let's trace through a complete example that demonstrates both proper command-line argument handling and the single logical line per physical line convention. This program will calculate the sum of two numbers passed as command-line arguments.

python
Output (expected)
When run as: python add.py 7.5 3.2
The sum of 7.5 and 3.2 is 10.7

This program demonstrates three key practices: importing sys, checking argument count before accessing specific indices, and converting string arguments to the appropriate numeric type. Each statement occupies its own line, making the logic clear and easy to follow.

Why Python Differs from Other Languages

Many programming languages, such as C, Java, and JavaScript, require semicolons at the end of every statement. These languages use the semicolon as the statement terminator, so you can write multiple statements on one line and the language will still parse them correctly. Python takes a different approach: it uses the newline character as the statement terminator. In Python, a new line typically means a new statement, so semicolons are unnecessary. While Python does support semicolons for backward compatibility and for rare cases where you need to separate multiple statements on one line, the language's design philosophy encourages writing one logical line per physical line. This design choice makes Python code more readable and less prone to certain formatting errors.

LanguageStatement TerminatorMultiple Statements Per LinePython Convention
PythonNewline (implicit)Possible with semicolon, but discouragedOne logical line per physical line
C / Java / JavaScriptSemicolon (required)Common and expectedNot applicable

Practice: Build Your Own Argument Handler

MEDIUM

Write a Python program called greet_user.py that accepts a person's name and age as command-line arguments. The program should check that exactly two arguments are provided, convert the age to an integer, and print a message like 'Hello, Alice! You are 25 years old.' Make sure to follow the single logical line per physical line convention and do not use any semicolons.

Hints
  • Remember to import sys at the top of your file.
  • Use len(sys.argv) to check that exactly 3 elements are present (script name plus two arguments).
  • Convert sys.argv[2] to an integer using int() since ages are numbers.
  • Use an f-string or string concatenation to format your output message.
  • Each statement should be on its own line.

Summary

  1. Command-line arguments are values passed to a program when it is executed from the terminal. Python stores these arguments in the sys.argv list, where sys.argv[0] is the script name and sys.argv[1], sys.argv[2], etc. are the actual arguments.
  2. Always import sys at the top of your program before using sys.argv. Check the length of sys.argv before accessing specific indices to avoid IndexError exceptions.
  3. Remember that all elements of sys.argv are strings. Convert them to the appropriate type (int, float, etc.) before performing operations on them.
  4. Follow the single logical line per physical line convention: write one complete Python statement per line and never use semicolons to combine multiple statements on a single line. This makes your code more readable and maintainable.
  5. When writing command-line programs, validate user input by checking argument counts and handling errors gracefully. This makes your programs robust and user-friendly.

Key Takeaways

  • Command-line arguments are passed to Python programs via the sys.argv list, where sys.argv[0] is the script name and subsequent elements are the arguments provided by the user.
  • Always import sys, check the argument count before accessing specific indices, and convert string arguments to appropriate data types before using them in calculations.
  • Python's design philosophy emphasizes one logical line per physical line of code; never use semicolons to combine multiple statements, as this violates readability conventions and is rarely seen in professional Python code.
  • Validate command-line input by checking len(sys.argv) and handling missing or invalid arguments gracefully to create robust, user-friendly programs.
  • Python's newline-based statement termination differs from languages like C and Java that require explicit semicolons, reflecting Python's focus on code clarity and readability.