PythonMastery
beginner 12 min read · lesson 1 of 19 in Python Fundamentals

Introduction to Python

1 · The lesson

read

Python is a high-level, interpreted, dynamically-typed language designed to read like English. You write a line; the interpreter runs it. No compile step, no boilerplate ceremony, no semicolons to forget.

It runs the systems behind Instagram, Spotify recommendations, NASA mission tooling, every major ML framework, and the script your colleague uses to rename 4,000 photos. Same language, different toolboxes.

This lesson gets you fluent in the shape of Python — what an expression looks like, how the interpreter responds, how indentation works, and where to look when something breaks.


1. Your First Line

python
print("Hello, Python.")

Press ▶. The interpreter reads print, evaluates the string "Hello, Python.", and writes the result to your output. That's the entire transaction.

print is a function. The parentheses tell Python to call it with the argument inside. No call, no output:

python
print            # just the function object — nothing happens
print("Now I'm called.")

2. Expressions vs Statements

An expression has a value. A statement does something.

python
2 + 3                  # expression — evaluates to 5
x = 2 + 3              # statement — binds the name x to the value 5
print(x)               # statement — calls print with x's value

The REPL (interactive prompt) prints expression values automatically. A .py file does not — that's why you see explicit print(...) calls everywhere in scripts.

python
# In a script, this line runs but produces no visible output:
2 + 3

# This one prints:
print(2 + 3)

3. Indentation Is Syntax

Most languages use { } to group code. Python uses indentation — usually 4 spaces. The indentation isn't decoration; it's the grammar.

python
temperature = 32

if temperature < 40:
    print("Cold.")           # this line belongs to the if
    print("Wear a jacket.")  # so does this one
print("Done.")               # back at column 0 — runs always

Mix tabs and spaces and Python will refuse to run the file. Pick one (4 spaces is convention) and stick with it. Every modern editor handles this for you.


4. Comments

python
# A comment starts with # and runs to the end of the line.
x = 41 + 1              # comments can sit at the end of code lines, too

"""
A triple-quoted string at the top of a function or file
acts as documentation. It's not technically a comment —
it's a string the interpreter ignores when unused.
"""

See Comments & Style for the conventions that separate readable code from noise.


5. Errors Are Friends

Make a typo deliberately:

python
prnit("Hello")          # NameError: name 'prnit' is not defined
+ setup added so this can run · defines prnit
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

def prnit(*_a, **_kw):
    print('-> prnit() called')
    return _AutoMock('prnit()')

The traceback tells you exactly what went wrong and on what line. Read errors top-to-bottom; the last line is usually the most useful. Three you'll see constantly:

  • SyntaxError — Python couldn't parse the code. Usually a missing : or unmatched (.
  • NameError — you used a name Python doesn't know. Usually a typo.
  • TypeError — you used something in a way its type doesn't allow. E.g. "3" + 3.

You'll get a dedicated lesson on this in Errors & Exceptions.


6. The Zen of Python

python
import this

Run it. You'll see 19 short aphorisms that capture how Python is designed to feel. Two worth memorising now:

Readability counts.
There should be one — and preferably only one — obvious way to do it.

Code is read ten times more than it's written. Optimise for the reader.


Common Mistakes

  • Forgetting the parentheses on print. print "hi" was Python 2. Python 3 requires print("hi").
  • Inconsistent indentation. IndentationError means you mixed widths or levels. Re-indent the whole block.
  • Using = for comparison. = assigns, == compares. We'll cover this in Operators.
  • Trying to assign to a literal. 5 = x is backwards — the name goes on the left.

🎯 Your Turn — Build a Mini Greeter

Write a small program that:

1. Stores your name in a variable.
2. Stores your favourite language in a variable.
3. Prints a single sentence using both, like "Hi, I'm Linus — I'm learning Python."
4. Then prints a second sentence on a new line saying how many letters are in your name.

Skeleton:

python
# TODO 1: bind your name and language to variables
name = ...
language = ...

# TODO 2: print a greeting that uses both
# TODO 3: print the length of your name
#         (hint: there's a built-in function for length)
Hint 1 — Strings inside strings You can build a sentence with + (e.g. "Hi, " + name), but the cleaner way is an f-string: f"Hi, I'm {name}". The {name} placeholder gets replaced with the variable's value.
Hint 2 — Length of anything len(x) returns the length of a string, list, or anything sized. len("hello") → 5.
Show full solution
python
name = "Linus"
language = "Python"

print(f"Hi, I'm {name} — I'm learning {language}.")
print(f"My name has {len(name)} letters.")

Two f-strings, one len() call. That's the whole program. You've just used variables, strings, function calls, and string interpolation — the four most common operations in any Python file you'll ever write.


What You Learned

  • Python runs line-by-line; no compile step.
  • Expressions have values; statements do things. Scripts need print() to show values; the REPL shows them automatically.
  • Indentation is syntax — 4 spaces, no mixing.
  • Tracebacks tell you what broke and where. Read bottom-up.
  • import this is a 1-minute philosophy lesson worth re-reading every year.

Next: Variables & Data Types — naming things and the handful of built-in types you'll see everywhere.

Practice this

on practicepython.in

Short exercises that run in your browser and tell you what your code actually did, not just whether a test passed.