Prerequisite:

Python is one of the best first languages you can learn. It reads almost like English, runs immediately without a compilation step, and has a library for nearly everything. This post gets you from zero to writing real programs.

Why Python

Three things make Python stand out for beginners:

Readable syntax. Python uses indentation instead of curly braces, so code structure is visible rather than hidden. if x > 0: followed by indented lines is unambiguous.

Huge ecosystem. Data science, web backends, automation, machine learning - Python has mature libraries for all of it. You won’t outgrow it quickly.

Interpreted. You don’t compile Python. You write it and run it. This makes experimentation fast.

Running Python: REPL vs Scripts

The REPL (Read-Eval-Print Loop) is a live session where you type expressions and see results immediately. Start it with python3 in your terminal:

>>> 2 + 2
4
>>> "hello".upper()
'HELLO'

For anything longer than a few lines, write a .py file and run it:

python3 my_script.py

Use the REPL to explore. Use scripts to save your work.

Variables and Types

Python is dynamically typed - you don’t declare types, the interpreter figures them out:

x = 10          # int
price = 3.99    # float
name = "Alice"  # str
active = True   # bool

The four core types are int, float, str, and bool. You can check what type a value is with type(x).

Dynamic typing means a variable can be reassigned to a different type. That’s flexible, but it means you need to pay attention to what a variable actually holds.

F-strings are the modern way to embed values in strings:

name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")

Built-in Data Structures

Python ships with four essential collection types.

List - ordered, mutable, indexed from 0:

fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
print(fruits[0])  # apple

Tuple - ordered, immutable (can’t be changed after creation):

point = (3, 4)
x, y = point  # unpacking

Dict - key-value pairs, fast lookup:

scores = {"Alice": 95, "Bob": 87}
scores["Carol"] = 91
print(scores["Alice"])  # 95

Set - unordered collection of unique items:

tags = {"python", "beginner", "python"}  # duplicate removed
print(tags)  # {'python', 'beginner'}

Control Flow

if/elif/else:

x = 15
if x > 20:
    print("large")
elif x > 10:
    print("medium")
else:
    print("small")

for loops iterate over any sequence:

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

for i in range(5):  # 0, 1, 2, 3, 4
    print(i)

while runs as long as a condition holds:

count = 0
while count < 3:
    print(count)
    count += 1

Use break to exit a loop early, and continue to skip to the next iteration.

Comprehensions

Comprehensions are compact expressions for building lists (or dicts/sets) from other iterables:

squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

Read it as: “for each x in 0–9, if x is even, include x squared.” This replaces a four-line for loop with one readable line.

Functions

Functions group code under a name so you can reuse and test it:

def greet(name, greeting="Hello"):
    """Return a greeting string."""
    return f"{greeting}, {name}!"

print(greet("Alice"))           # Hello, Alice!
print(greet("Bob", "Hi"))       # Hi, Bob!

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict:

def summarise(*numbers):
    return sum(numbers) / len(numbers)

print(summarise(10, 20, 30))  # 20.0

The Import System

Python’s standard library and third-party packages are accessed via import:

import math
print(math.sqrt(16))  # 4.0

from collections import Counter
words = ["apple", "banana", "apple", "cherry"]
print(Counter(words))  # Counter({'apple': 2, 'banana': 1, 'cherry': 1})

Common Gotchas

Mutable default arguments. Never use a list or dict as a default argument value:

# WRONG - the same list is shared across all calls
def add_item(item, items=[]):
    items.append(item)
    return items

# RIGHT
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

is vs ==. == checks value equality. is checks identity (same object in memory). Use == for comparisons; is is for checking None:

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)   # True  (same value)
print(a is b)   # False (different objects)
print(a is None)  # False

Examples

FizzBuzz - the classic programming exercise:

for n in range(1, 101):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Word frequency counter - combining loops, dicts, and the standard library:

from collections import Counter

text = "the quick brown fox jumps over the lazy dog the fox"
words = text.split()
freq = Counter(words)

for word, count in freq.most_common(3):
    print(f"{word}: {count}")
# the: 3
# fox: 2
# quick: 1

These two programs touch almost everything covered in this post: control flow, data structures, functions, and imports. Once you can write programs like these without looking things up, you have a solid Python foundation.


Read Next: