Python: Python Syntax & Variables
Now it's time to start writing real Python code. Let's cover the most fundamental rules: indentation, comments, and variables.
1. Indentation Rules
Python's most distinctive feature — it uses indentation to define code blocks instead of curly braces {}.
TEXT
📖 Display only
# ✅ Correct: consistent indentation within a block
if 3 > 1:
print("3 is greater than 1")
print("This line is also inside the if block")
# ❌ Error: inconsistent indentation
if 3 > 1:
print("3 is greater than 1")
print("Wrong indentation!") # IndentationError
⚠️ Golden rule: Always use 4 spaces for indentation, never tabs. Most editors (VS Code, PyCharm) will automatically convert a Tab press to 4 spaces.
Indentation applies not just to if statements, but to all code blocks — loops, functions, classes, and more:
PYTHON
# Indentation in a for loop
for i in range(3):
print(i) # This line is inside the loop
print("---") # This line is also inside the loop
print("Done") # This line is NOT inside the loop
2. Comments
Comments are for human readers — Python ignores them completely.
(1) Single-line Comments: #
PYTHON
# This is a single-line comment
print("Hello") # Comment after code
# Multi-line comments use multiple # symbols
# This is line two
# This is line three
(2) Multi-line String Comments: """ """ or ''' '''
Technically these are strings, but they're commonly used as multi-line comments:
PYTHON
"""
This is a multi-line comment
Useful for writing function descriptions
Or temporarily blocking out large blocks of code
"""
print("The multi-line string above won't execute")
3. Variables
Python variables don't need type declarations — just assign a value and you're good to go:
PYTHON
name = "Alice" # str
age = 25 # int
height = 1.75 # float
is_student = True # bool
(1) Variable Naming Rules
| Rule | Correct ✅ | Incorrect ❌ |
|---|---|---|
| Letters, digits, underscores only | my_name |
my-name |
| Cannot start with a digit | var1 |
1var |
| Case-sensitive | name and Name are different |
- |
| Cannot be a keyword | - | if, for, class |
(2) Naming Conventions (PEP 8)
PYTHON
# ✅ Variables: lowercase with underscores (snake_case)
user_name = "Alice"
total_price = 99.9
max_value = 100
# ✅ Constants: ALL_CAPS with underscores
PI = 3.14159
MAX_SIZE = 1024
# ❌ Not recommended
userName = "Alice" # CamelCase (Java style)
UserName = "Alice" # Looks like a class name
(3) Multiple Variable Assignment
Python lets you assign multiple variables in one line:
PYTHON
# Assign multiple values at once
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Swap two variables (other languages need a temporary variable)
x, y = 10, 20
x, y = y, x
print(x, y) # 20 10
# Assign the same value to multiple variables
m = n = p = 0
print(m, n, p) # 0 0 0
▶ Example: Variable Types and Swapping (Difficulty ⭐)
PYTHON
# Define variables of different types
name = "Alice"
age = 25
height = 1.68
is_student = True
# Print variable info
print(f"{name} is {age} years old, {height}m tall")
print(f"Student status: {is_student}")
# Swap two variables
a, b = 10, 20
print(f"Before: a={a}, b={b}")
a, b = b, a
print(f"After: a={a}, b={b}")
# Check types
print(f"name type: {type(name)}")
print(f"age type: {type(age)}")
print(f"height type: {type(height)}")
Output:
TEXT
📖 Display only
Alice is 25 years old, 1.68m tall
Student status: True
Before: a=10, b=20
After: a=20, b=10
name type: <class 'str'>
age type: <class 'int'>
height type: <class 'float'>
4. The type() Function
▶ Example: Variable Type Exploration (Difficulty ⭐)
PYTHON
# Explore different types and conversions
x = 42
y = 3.14
z = "Hello"
w = True
print(f"x = {x}, type = {type(x).__name__}")
print(f"y = {y}, type = {type(y).__name__}")
print(f"z = {z}, type = {type(z).__name__}")
print(f"w = {w}, type = {type(w).__name__}")
# Type conversion
print(f"\nint(y) = {int(y)}")
print(f"float(x) = {float(x)}")
print(f"str(x) = {str(x)}")
print(f"bool(0) = {bool(0)}, bool(1) = {bool(1)}")
# Dynamic typing: variable can change type
var = 100
print(f"\nvar = {var}, type = {type(var).__name__}")
var = "now a string"
print(f"var = {var}, type = {type(var).__name__}")
Output:
TEXT
📖 Display only
x = 42, type = int
y = 3.14, type = float
z = Hello, type = str
w = True, type = bool
int(y) = 3
float(x) = 42.0
str(x) = 42
bool(0) = False, bool(1) = True
var = 100, type = int
var = now a string, type = str
▶ Example: Variable Assignment Tricks (Difficulty ⭐)
PYTHON
# Multiple assignment
a, b, c = 10, 20, 30
print(f"a={a}, b={b}, c={c}")
# Swap without temp variable
x, y = 100, 200
print(f"Before swap: x={x}, y={y}")
x, y = y, x
print(f"After swap: x={x}, y={y}")
# Same value to multiple variables
p = q = r = 0
print(f"p={p}, q={q}, r={r}")
# Unpacking a list
colors = ["red", "green", "blue"]
first, second, third = colors
print(f"First: {first}, Second: {second}, Third: {third}")
Output:
TEXT
📖 Display only
a=10, b=20, c=30
Before swap: x=100, y=200
After swap: x=200, y=100
p=0, q=0, r=0
First: red, Second: green, Third: blue
4. The type() Function
Use type() to check a variable's type:
PYTHON
print(type(10)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
# Variables can change type when reassigned (dynamic typing)
x = 10
print(type(x)) # <class 'int'>
x = "Hello"
print(type(x)) # <class 'str'> ← type changed
5. Common Errors
PYTHON
# IndentationError: wrong indentation
print("Too much indentation")
print("This line has an extra space") # ❌
# NameError: variable not defined
print(z) # ❌ z was never assigned
# SyntaxError: invalid syntax
print("Hello) # ❌ quotes not closed
❓ FAQ
Q Why does Python use indentation instead of braces
{} like other languages?A Python's creator, Guido van Rossum, believed code should be readable by humans first. Indentation visually represents code structure — your eye already sees it, so why require extra symbols? This forces consistent formatting and eliminates entire categories of bugs (missing braces, mismatched brackets). It's a design philosophy: "Beautiful is better than ugly."
Q I mixed tabs and spaces — my code looks fine but throws an
IndentationError. Why?A Python treats tabs and spaces as different characters. A line indented with a tab looks the same as one indented with 4 spaces to your eye, but Python sees them differently. The fix: configure your editor to convert tabs to spaces (VS Code does this by default). Use
python -m tabnanny myfile.py to scan for mixed indentation.Q What's the difference between Python's dynamic typing and static typing in languages like Java? Does it matter?
A In statically typed languages, you declare a variable's type upfront (
int x = 5;) and it can't change. In Python, types are determined at runtime and can change (x = 5; x = "hello" works). Dynamic typing is more flexible and faster to write, but type errors only surface at runtime. For beginners, dynamic typing means less boilerplate; for large projects, static typing catches bugs earlier.Q I keep getting
NameError: name 'xxx' is not defined. How do I fix this?A NameError means Python can't find a variable with that name. Common causes: ① Typo in the variable name (Python is case-sensitive —
Name ≠ name); ② Using a variable before assigning it; ③ Variable was defined inside a function or loop but you're trying to access it outside. Quick fix: add print() before the error line to check what variables actually exist at that point.Q What's the difference between
= and ==? I keep mixing them up.A
= is assignment — it puts a value into a variable (x = 5 means "x now holds 5"). == is comparison — it asks "are these equal?" (x == 5 returns True or False). Think of = as an arrow pointing left (x ← 5) and == as a balance scale checking both sides. This is one of the most common beginner mistakes — writing if x = 5: instead of if x == 5:.📖 Summary
- Python uses 4 spaces of indentation to organize code blocks
- Single-line comments use
#, multi-line comments use""" """ - Variables are assigned directly — no type declaration needed (dynamic typing)
- Variable names use
snake_case(lowercase + underscores) - Constants use
ALL_CAPSlikeMAX_VALUE - Use
type()to check a variable's type - You can assign multiple variables at once:
a, b = 1, 2
📝 Exercises
- Write code that defines three variables:
city(city name),year(year),score(score 88.5), and print them usingprint() - Swap two variables
a = 5andb = 10so thatabecomes 10 andbbecomes 5 - Use
type()to check the types ofTrue,"123", and3.0 - Intentionally write code with an indentation error, see what error Python throws, and take a screenshot of the error message