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

Introduction to Python

1 · The lesson

read

Python is a programming language that was designed to be easy to read. Its code often looks close to plain English. You write a line, and a program called the interpreter runs it straight away. You don't need a separate step to turn your code into a program first, and you don't need a semicolon at the end of every line.

Python is used at Instagram, Spotify and NASA, and it is the main language for machine learning. It is also used for small scripts, like one that renames 4,000 photos. It is the same language in every case. Only the libraries change.

This lesson shows you the basic shape of Python code: what an expression looks like, how the interpreter responds, how indentation works, and where to look when something goes wrong.


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 is all that happens.

print is a function. The parentheses tell Python to call it with the argument inside. If you leave out the parentheses, the function is not called and nothing is printed:

python
print            # names the function but does not call it, so nothing happens
print("Now I'm called.")

2. Expressions vs Statements

An expression has a value. A statement does something.

python
2 + 3                  # expression: its value is 5
x = 2 + 3              # statement: makes the name x refer to the value 5
print(x)               # statement: calls print with the value of x

The REPL (interactive prompt) prints expression values automatically. A .py file does not. That is why scripts use print(...) every time they need to show a value.

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 is part of the language's rules. If it is wrong, Python raises an error or the code does something different.

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, so it always runs

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 is not really a comment.
It is a string that Python ignores when nothing uses it.
"""

See Comments & Style for the conventions that make code easy to read.


5. Errors Help You

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 error message (called a traceback) tells you what went wrong and on which line. Start reading at the last line: it names the error and is usually the most useful line. The lines above it show where the error happened. Three errors you will see often:

  • SyntaxError: Python couldn't read the code. Usually a missing : or unmatched (.
  • NameError: you used a name Python doesn't know. Usually a typo.
  • TypeError: you used a value 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 sayings that describe the ideas behind Python's design. Two are worth remembering now:

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

Code is read much more often than it is written, so write it for the person who will read it.


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.

The cleanest way to build these sentences is an f-string, which the f-strings lesson covers fully. Hint 1 shows the one form you need. You can also join strings with + instead.

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 and one len() call: that is the whole program. You have just used variables, strings, function calls and string interpolation. You will use these four things in almost every Python file you write.


What You Learned

  • Python runs line-by-line, with no compile step.
  • Expressions have values, and statements do things. Scripts need print() to show values, but the REPL shows them automatically.
  • Indentation is syntax: use 4 spaces, and don't mix tabs and spaces.
  • Tracebacks tell you what went wrong and where. Start with the last line.
  • import this prints the Zen of Python, a short list of Python's design ideas.

Next: Variables & Data Types, where you learn to name values and meet the built-in types you will use most.

Practice this

on practicepython.in

Short exercises that run in your browser and tell you what your code did, as well as whether a test passed.

Found this useful? Share it with a friend who’s learning Python.