Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python Module 1 – Getting started: install, run and read Python

The Python REPL, scripts and the -m switch

Explore values in the interactive Python shell, run scripts, one-liners and modules with python3, -c and -m, and read command-line arguments from sys.argv.

  • Beginner
  • 15 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot

What you will learn

  • Use the interactive shell to explore values with help() and dir()
  • Run a script, a module with -m and a one-liner with -c
  • Read command-line arguments from sys.argv

Before you start

On this page

There are three ways to give Python some code: type it into the interactive shell, save it in a file and run the file, or pass it on the command line. Each has its place, and knowing which one you are in explains a lot of “it worked here but not there” surprises.

The interactive shell

Run python3 (on Windows, py) with nothing after it. Python prints a short banner and the >>> prompt: you are in the interactive shell, also called the REPL, for read, evaluate, print, loop. Type an expression and press Enter; Python evaluates it and prints its value:

A short session in the shell Python console · repl_session.pycon
>>> 2 ** 100
1267650600228229401496703205376
>>> _ * 2
2535301200456458802993406410752
>>> name = "Asha"
>>> name.upper()
'ASHA'
>>> "upper" in dir(name)
True

This session was replayed with Python 3.14.8 on macOS 26 arm64, and it printed exactly what is shown.

Lines starting with >>> are what was typed; the others are what Python printed. Four things to notice:

  • ** raises a number to a power, so 2 ** 100 is 21002^{100}. Python’s whole numbers have no size limit, so the shell prints all 31 digits instead of rounding the result.
  • The shell prints the value of an expression by itself. A script does not: there you need print().
  • _ (an underscore) holds the last value the shell printed, which saves retyping it. It only works in the shell.
  • dir(name) lists the names an object has, its methods and attributes; help(name.upper) shows the documentation of one of them. In a help page, press q to get back to the prompt.

To leave the shell, type exit (in the older basic shell, exit()), or press Ctrl-D on macOS and Linux, or Ctrl-Z and then Enter on Windows.

Version note

Since Python 3.13 the shell lets you edit a whole block of several lines and keeps your history. Python 3.14 adds syntax colours and completes module names after import when you press Tab. If your terminal has trouble with the new shell, set the environment variable PYTHON_BASIC_REPL to 1 to get the simpler one.

The shell is for trying things out. Anything you want to keep belongs in a file.

Running a script

A script is a file of Python code. python3 hello.py runs the file hello.py from the current folder, from the first line to the last, and exits. Add -i (python3 -i hello.py) to stay in the interactive shell after the script has finished, with all its variables still there to inspect.

One-liners with -c

For a quick calculation, pass the code itself with -c: python3 -c "print(2 ** 100)". Put the code in quotes so the terminal hands it to Python as one piece.

Version note

New in Python 3.14: the code after -c is dedented first, so an indented block pasted from a file works. Python 3.12 rejects the same text with IndentationError: unexpected indent.

Running modules with -m

python3 -m name finds the module called name, the way import name would, and runs it as a program. Many standard-library modules are useful this way:

  • python3 -m venv .venv creates a virtual environment (a later lesson).
  • python3 -m pip install … installs packages with pip.
  • python3 -m json data.json checks a JSON file and prints it neatly indented (new in 3.14; python3 -m json.tool also works).
  • python3 -m http.server serves the files of the current folder at http://localhost:8000/ until you press Ctrl-C. Other devices on your network can reach it too, so run it only in a folder you are happy to share.

The module comes from the same interpreter as the python3 you typed. That is why python3 -m pip is the safe way to install packages: it installs them for that Python, even when a pip command on your PATH belongs to another one.

Command-line arguments with sys.argv

Words you type after the script’s name reach the program in sys.argv, a list of strings. Item 0 is the script’s name as you typed it; the arguments follow:

Reading command-line arguments Python · args_demo.py
import sys

# A terminal fills sys.argv from the command line:  python3 args_demo.py Asha 3
# A browser has no command line, so when no arguments were given we set the same list here.
if len(sys.argv) <= 1:
    sys.argv = ["args_demo.py", "Asha", "3"]

print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
print("Number of arguments:", len(sys.argv) - 1)

Output

Script name: args_demo.py
Arguments: ['Asha', '3']
Number of arguments: 2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 args_demo.py

Run it as python3 args_demo.py Ravi 5 extra and it prints those three arguments instead. A browser has no command line, so when the program gets no arguments, as in a browser runner, it sets the list itself, the way a terminal would have.

Warning

Every argument is a string, even 3. Convert it before doing arithmetic: int(sys.argv[2]). For programs with options and help text, the argparse module (covered later in this track) does the parsing for you.

Python Online Compiler Try the shell's examples as a script: wrap each expression in print().

Key takeaways

  • python3 alone starts the interactive shell, which prints each value; leave it with exit or Ctrl-D (Ctrl-Z and Enter on Windows).
  • python3 file.py runs a script, -i keeps the shell open afterwards, and -c "code" runs a one-liner.
  • python3 -m module runs a module with the same interpreter, which is why python3 -m pip installs to the right Python.
  • sys.argv holds the script name and the arguments, all as strings.

Exercise

Exercise · Easy · Python

Read a name and a count from the command line

A program reads its arguments from sys.argv; a function that takes that list as a parameter is easier to test. Write parse_args(argv) for a program used as greet.py NAME [COUNT], where the square brackets mean that the count may be left out.

- argv is a list like sys.argv: the program's name first, then the arguments, all of them strings. - Return a tuple (name, count) with count as a whole number: parse_args(["greet.py", "Asha", "3"]) returns ("Asha", 3). - When the count is left out it is 1: parse_args(["greet.py", "Ravi"]) returns ("Ravi", 1). - When the name is missing, there are too many arguments, or the count is not a whole number of at least 1, raise SystemExit with the message usage: greet.py NAME [COUNT].

raise SystemExit("usage: greet.py NAME [COUNT]") stops a program with that message, the way sys.exit() with a message does.

Starter code · greet.py

def parse_args(argv):
    """Return (name, count) from a list like sys.argv, or stop with the usage message."""
    name = argv[1]
    count = argv[2]
    return name, count
The sample tests · test_greet.py
from greet import parse_args

USAGE = "usage: greet.py NAME [COUNT]"


def exits_with_usage(argv):
    """True when parse_args(argv) stops the program with the usage message."""
    try:
        parse_args(argv)
    except SystemExit as stop:
        return str(stop.code) == USAGE
    return False


def test_name_and_count():
    """reads the name and the count as a number"""
    assert parse_args(["greet.py", "Asha", "3"]) == ("Asha", 3)
    assert parse_args(["greet.py", "Mei", "1"]) == ("Mei", 1)


def test_count_defaults_to_one():
    """uses 1 when the count is left out"""
    assert parse_args(["greet.py", "Ravi"]) == ("Ravi", 1)


def test_missing_name():
    """stops with the usage message when the name is missing"""
    assert exits_with_usage(["greet.py"])


def test_bad_count():
    """stops with the usage message for a count that is not a whole number of at least 1"""
    assert exits_with_usage(["greet.py", "Asha", "three"])
    assert exits_with_usage(["greet.py", "Asha", "0"])
    assert exits_with_usage(["greet.py", "Asha", "-2"])


def test_too_many_arguments():
    """stops with the usage message when there are extra arguments"""
    assert exits_with_usage(["greet.py", "Asha", "3", "extra"])
A hint

Check how many items argv has before you read them: len(argv) is 2 with a name only and 3 with a name and a count. "3".isdigit() is True and "three".isdigit() is False, so check the text before you call int() on it.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Check yourself

5 questions about this lesson. Every answer and why it is right is on the page, behind “Show the answer”. Your score stays in this browser.

  1. Question 1 of 5 What does args_demo.py print when it runs with no arguments, as in a browser?

    What does this program print? Choose one answer.

    import sys
    
    # A terminal fills sys.argv from the command line:  python3 args_demo.py Asha 3
    # A browser has no command line, so when no arguments were given we set the same list here.
    if len(sys.argv) <= 1:
        sys.argv = ["args_demo.py", "Asha", "3"]
    
    print("Script name:", sys.argv[0])
    print("Arguments:", sys.argv[1:])
    print("Number of arguments:", len(sys.argv) - 1)
    Show the answer to question 1

    Answer: it prints

    Script name: args_demo.py
    Arguments: ['Asha', '3']
    Number of arguments: 2

    With no arguments the program sets sys.argv to ["args_demo.py", "Asha", "3"]. Item 0 is the script's name, sys.argv[1:] holds the arguments, and every argument is a string, so the 3 prints as '3'.

  2. Question 2 of 5 In the interactive shell, what does _ (an underscore) hold?

    Choose one answer.

    Show the answer to question 2

    Answer: The last value the shell printed

    The shell keeps the last value it printed in _, so _ * 2 uses it without retyping. It is a feature of the shell only: in a script, _ has no special meaning.

  3. Question 3 of 5 Which commands run the standard library's json module as a program on data.json?

    Choose every answer that is right.

    Show the answer to question 3

    Answer:

    • python3 -m json.tool data.json
    • python3 -m json data.json

    -m runs a module by its import name. python3 -m json works from Python 3.14 on, and python3 -m json.tool works too. Without -m, python3 json looks for a file called json, and -c expects Python code.

  4. Question 4 of 5 You run this file as python3 show.py 3. What does it print?

    Read the code, then choose one answer.

    import sys
    print(type(sys.argv[1]).__name__)
    Show the answer to question 4

    Answer: str

    Every command-line argument reaches the program as a string, even when it looks like a number, so the type is str. Convert it with int(sys.argv[1]) before doing arithmetic.

  5. Question 5 of 5 The shell prints 2 ** 100 in full. How many digits does it have?

    Type a number.

    Show the answer to question 5

    Answer: 31 digits

    2 ** 100 is 1267650600228229401496703205376, 31 digits. Python's whole numbers grow as large as needed, so the shell prints every digit instead of rounding the result.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.