AlgoInsight

Free lesson · Python Basic to Advance

Your First Program

Easy6 min readpython

Your First Python Program

The Simplest Possible Program

A complete Python program can be a single line in a single file.

Create a file named hello.py with one line:

print("Hello, Python")
This single line calls Python's built-in print function with the string Hello comma Python. When run, it displays that text to the terminal.

Run it from a terminal:

python hello.py
This shell command runs the Python interpreter on the file hello.py.

The output:

Hello, Python
The output is the literal text Hello comma Python, followed by a newline.

That's a complete program. No boilerplate. No main function. No class wrapper. No imports. The line at file scope executes when the file runs.

This minimal example illustrates one of Python's design choices: simple things should be simple. Compare to the Java equivalent, which requires a class declaration, a main method, and a System.out.println call. Python's version is one line because the language has no ceremony for trivial cases.

Interactive animation: One line in hello.py, run with python hello.py, prints Hello, Python - no class, no main, no imports.

Understanding What Just Happened

Interactive animation: Running python hello.py - the interpreter reads the source, compiles it to bytecode, runs it, then the process exits.

Three things occurred when the program ran:

  1. The Python interpreter read hello.py from disk.
  2. It compiled the file's contents to bytecode.
  3. It executed the bytecode, which made one call to the built-in print function with the string "Hello, Python" as argument.

The print function writes its argument to standard output, followed by a newline. The terminal displays the output. The program exits.

No type was declared. No memory was manually allocated or freed. No semicolon ended the statement. These are deliberate omissions; Python's design avoids them.

Variables and Slightly More Logic

A slightly more interesting program:

name = "Alice"
age = 30
print(f"{name} is {age} years old")
# Alice is 30 years old
This code assigns the string Alice to the variable name and the integer thirty to the variable age. It then uses an f-string to combine them into the message: Alice is thirty years old. The f-string prefix lets Python substitute variable values into the string at the positions marked with curly braces.

Three new things appear:

f-strings are covered in detail in Module 3. For now, they are the modern Python way to build strings that include variable values.

Interactive animation: Two variables and an f-string print Alice is 30 years old - no type declarations, the value decides the type.

Running Python Code Three Ways

Python code can be executed in three ways. Each has its use.

Running a Script

The most common way. Save code to a file and run it:

python hello.py
This shell command runs the Python script named hello dot py. The interpreter executes the file from top to bottom and exits when done.

The interpreter executes the file top to bottom and exits.

The Interactive REPL

Run python (or python3) with no arguments to start the Read-Eval-Print Loop:

$ python
Python 3.13.0 (main, ...)
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Alice"
>>> print(name)
Alice
>>> 2 + 2
4
>>>
This shows an interactive Python REPL session. The user typed python at the shell prompt, which started the interpreter and printed the version banner. The user then assigned the string Alice to name, printed name, which output Alice, and evaluated two plus two, which output four. The triple-arrow prompt indicates the REPL is ready for the next input.

Each line is evaluated immediately. The REPL is useful for exploring language features, testing snippets, and debugging.

Exit with exit() or by pressing Ctrl-D (macOS/Linux) or Ctrl-Z then Enter (Windows).

One-Liners

Execute a single line of Python from the command line:

python -c "print('Hello, Python')"
This shell command uses Python's dash-c flag to execute a single statement: a print call that outputs Hello comma Python.

Useful for scripting, quick checks, or shell integration. The -c flag takes a Python statement as a string argument.

A More Realistic First Program

A program that does something marginally useful:

def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old"

message = greet("Alice", 30)
print(message)
# Alice is 30 years old
This code defines a function called greet that takes two parameters: name typed as a string and age typed as an integer. The arrow str declares that the function returns a string. The function body returns an f-string combining the two values. The code then calls greet with the arguments Alice and thirty, stores the result in message, and prints it. The output is: Alice is thirty years old.

This introduces:

The function greet takes two parameters and returns a string. The name: str syntax is a type hint - it declares that name should be a string. Python does not enforce type hints at runtime; they are documentation and tools-checked information.

This program is still tiny but uses the patterns that scale to real code.

What Goes in a Python File

A Python source file is just text with the .py extension. The contents can include:

A typical file:

"""
A module that demonstrates a simple Python file structure.
"""

import math

PI_SQUARED = math.pi ** 2

def circle_area(radius: float) -> float:
    """Compute the area of a circle given its radius."""
    return math.pi * radius ** 2

def main() -> None:
    print(f"Area of unit circle: {circle_area(1.0)}")

if __name__ == "__main__":
    main()
This example shows a typical Python file structure. At the top is a module docstring describing the file's purpose. Below it is an import of the math standard library module. A constant PI_SQUARED is defined as math dot pi raised to the second power. The circle_area function takes a float radius and returns the area as a float, using the formula pi times radius squared. The main function calls circle_area with 1.0 and prints the result. The if dunder name dunder equals dunder main dunder guard at the bottom ensures main runs only when this file is executed directly, not when imported.

This structure becomes the standard pattern as code grows:

The if __name__ == "__main__": line is a Python idiom that means "only run this code when the file is executed directly, not when it's imported by another file." It's covered in detail in Module 11.

Where Most Programs Live

In professional Python work, programs are rarely single files run directly. They are organized into packages with multiple modules, run as installed commands or web services. Single-file scripts remain useful for:

The course progresses from single-file programs to multi-file packages over the early modules.

Interactive animation: Where programs grow - one file, then several modules, then an installed package, then a command or a service.

Interview Relevance

Interview: Coding interviews almost always begin with single-file programs. Knowing the basics - script structure, the if __name__ == "__main__": idiom, function definitions - is assumed. Interviewers do not test these directly but expect fluency.

Module 30 covers Python interview preparation.

Common Pitfalls

Warning: Missing colons after def, if, for, etc. Python requires colons to introduce blocks. Forgetting them is the most common syntax error.

Mixing tabs and spaces for indentation. Python's indentation rules don't tolerate mixed whitespace. Use spaces consistently (4 spaces per level).

Forgetting parentheses on print. Python 3 requires print(...). Python 2's print ... syntax is invalid.

Putting top-level code without the __main__ guard. Code at file scope runs when the file is imported, not just when executed. The guard prevents this.

Naming a file the same as a standard library module. A file named random.py shadows the built-in random module and causes confusing import errors.

Try It

Exercise: Build fluency with the basics:

  1. Write a one-line program that prints your name.
  2. Open the REPL and compute 2 ** 100. Note that Python handles arbitrary integer sizes.
  3. Write a function that takes two numbers and returns their average. Call it with several inputs.
  4. Write a small program with the full standard structure (docstring, imports, constants, function, if __name__ == "__main__": guard).
  5. Run the same program in three ways: as a script, in the REPL (paste line by line), and as a one-liner with python -c.

Back to Python Basic to Advance