📘 Lesson 03 · Beginner

Python Syntax

Learn Python's clean syntax rules — indentation, comments, variables, and how Python code is structured.

Indentation — Python's Core Rule

Unlike most languages that use curly braces {} to group code blocks, Python uses indentation (whitespace at the start of a line). This is not optional — it is part of the language syntax itself. The convention is 4 spaces per level. Python enforces this consistently, which means all Python code looks similar regardless of who wrote it.

indent.py
if 5 > 2:
    print("Five is greater!")    # 4 spaces = inside the block
    print("This also runs")        # still inside
print("Back outside the if")         # zero indent = outside
▶ Output
Five is greater!
This also runs
Back outside the if
⚠️
Mixing tabs and spaces causes IndentationError and crashes your program. Always use 4 spaces. Configure your editor to insert spaces when Tab is pressed.

Comments

Comments are notes for humans — Python ignores them completely. Use # to comment out a single line or add a note after code. For longer multi-line descriptions (especially inside functions), use triple-quoted strings called docstrings. Writing good comments is a sign of professional code — explain why something is done, not just what it does.

comments.py
# Single-line comment
print("Hello")  # inline comment after code

# Temporarily disable code:
# print("This won't run")

"""
Multi-line docstring.
Used to document functions and classes.
"""
print("After the comment block")
▶ Output
Hello
After the comment block

Variables and Assignment

In Python, a variable is created the moment you assign a value to it — no prior declaration needed. Python uses dynamic typing, meaning it infers the type from the value you assign. You can also assign multiple variables in one line, or swap two variables elegantly without a temporary variable — something that requires 3 lines in most other languages.

vars.py
x = 10            # integer
name = "Python"   # string
pi = 3.14159      # float

# Multiple assignment on one line
a, b, c = 1, 2, 3
print(a, b, c)

# Elegant swap — no temp variable needed
a, b = b, a
print(a, b)
▶ Output
1 2 3
2 1

Line Continuation

When a statement is too long for one line, wrap it in parentheses — Python knows the expression continues until the closing bracket. This is the preferred style. Alternatively, end a line with a backslash \, though parentheses are cleaner.

lines.py
# Long expression split across lines (parentheses preferred)
total = (100 + 200 +
          300 + 400)
print(total)

# Long print broken up
print("The total is:",
      total,
      "units")
▶ Output
1000
The total is: 1000 units
Write one statement per line. Squeezing multiple statements onto one line with ; is valid but considered bad Python style.

🧠 Quick Check

How many spaces does Python use per indentation level?

2
3
4
8

Tags

syntaxindentationcommentsvariablespython ruleswhitespace