Python Syntax Basics
Python has the cleanest, most readable syntax of any popular programming language. Unlike Java or C++, there are no semicolons, no curly braces, and code reads almost like plain English. This chapter covers every core syntax rule you need to write correct Python from day one.
What Makes Python Syntax Special?
Every programming language has a set of rules — called syntax — that defines how you write valid code. Python was designed with one core goal: readability first. Its creator Guido van Rossum built it so that Python code looks similar to pseudocode or plain English.
; needed at end of
each statement like in Java or C.{ }.
Indentation is mandatory and meaningful.age, Age
and AGE are three completely different variables.# on a line is a comment —
Python ignores it completely.int x = 5. Just write x = 5 — Python figures the type automatically.import this in any Python shell to see Python's 19 guiding principles.
The most important one: "Readability counts."
Indentation — Python's Most Important Rule
In most languages, indentation is optional — just a style choice. In Python, indentation is mandatory. It tells Python which lines belong to which block of code. Get it wrong and your program crashes.
IndentationError and refuses to run your code. This is the #1 mistake new
Python developers make.
How indentation defines code blocks — visual diagram
# ✅ Standard: 4 spaces per level (PEP 8 standard)
if True:
print("Level 1") # 4 spaces
if True:
print("Level 2") # 8 spaces
if True:
print("Level 3") # 12 spaces
# ✅ You CAN use 2 spaces — just be consistent throughout the file
if True:
print("2-space indent") # 2 spaces — OK if used everywhere
# ❌ Mixing spaces and tabs → TabError in Python 3
if True:
print("tab") # tab ← DO NOT mix with spaces
print("space") # spaces ← will cause TabError!
Python Statements
A statement is a single instruction Python executes. In Python, each line is typically one statement, and it ends at the newline — no semicolons required.
# Each line is one statement — no semicolons needed
x = 10 # assignment statement
print(x) # function call statement
name = "Alice" # string assignment
result = x + 5 # expression statement
# You CAN put multiple statements on one line using semicolons
# (but it's bad style — avoid this)
a = 1; b = 2; c = 3 # ← works but NOT recommended
# Simple statements (one line)
pass # does nothing (placeholder)
break # used inside loops
continue # skip rest of loop iteration
return x # return from function
# Compound statements (span multiple lines, need colon + indented block)
if x > 5:
print("big") # body of the if block
for i in range(3):
print(i) # body of the for loop
x = 5), print(), return, import. No colon at the end.
: and an
indented body. Examples: if, for,
while, def, class.
print("hi"). Python evaluates it and discards the result unless it's
assigned.Variables in Python
A variable is a name that stores a value in memory. In Python, you
create a variable simply by assigning a value to a name — no type declaration, no var, no let. Python automatically figures
out the type.
# Create variables by assignment — no type keyword needed
name = "Alice" # str (string)
age = 25 # int (integer)
height = 5.7 # float
is_adult = True # bool (Boolean)
# Python infers the type — check with type()
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_adult)) # <class 'bool'>
# Reassign to a completely different type — Python allows it
x = 10
print(type(x)) # <class 'int'>
x = "hello"
print(type(x)) # <class 'str'> — changed!
# Assign multiple variables in one line
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Assign same value to multiple variables
x = y = z = 0
print(x, y, z) # 0 0 0
# Swap two variables (Python makes this elegant)
a, b = 10, 20
a, b = b, a # swap!
print(a, b) # 20 10
Variable Naming Rules & Conventions
Python has strict rules (break them → error) and recommended conventions (ignore them → ugly code). Learn both.
Hard Rules — violating these causes a SyntaxError
| Rule | Valid Example | Invalid Example | Reason |
|---|---|---|---|
| Start with letter or underscore | ✓ name ✓ _age | ✗ 2name | Cannot start with a digit |
| Letters, digits, underscores only | ✓ user_1 | ✗ user-1 ✗ user@ | No hyphens or special chars |
| No spaces allowed | ✓ first_name | ✗ first name | Use underscore instead |
| Cannot be a keyword | ✓ for_loop | ✗ for ✗ if | Reserved words are off-limits |
| Case sensitive | ✓ age ✓ Age (different) | — | Different variables entirely |
Conventions — PEP 8 recommendations every Python dev follows
# ── Variables and functions → snake_case (lowercase + underscores)
user_name = "Alice"
total_price = 99.99
def calculate_tax(price): ...
# ── Constants → UPPER_SNAKE_CASE (all caps)
MAX_SIZE = 100
PI = 3.14159
DATABASE_URL = "localhost:5432"
# ── Classes → PascalCase (each word capitalised)
class BankAccount: ...
class UserProfile: ...
# ── "Private" variables → single leading underscore (by convention)
_internal_counter = 0
# ── Throwaway / unused variable → single underscore
for _ in range(3):
print("Hello") # don't need the loop counter
# ── Good names are descriptive
x = 25 # ← bad: what is x?
user_age = 25 # ← good: meaning is clear
Python is Case-Sensitive
Python treats uppercase and lowercase letters as completely different. This applies to variable names, function names, class names, and keywords. This is one of the most common sources of bugs for beginners.
# These are THREE separate variables
name = "alice"
Name = "Bob"
NAME = "CAROL"
print(name, Name, NAME) # alice Bob CAROL
# Python keywords are all lowercase — capitalisation breaks them
print(True) # True ← works
print(False) # False ← works
print(None) # None ← works
# print(TRUE) ← NameError: name 'TRUE' is not defined
# print(true) ← NameError: name 'true' is not defined
# Functions are also case-sensitive
print("hello") # works
# Print("hello") ← NameError
# PRINT("hello") ← NameError
# Practical tip: be consistent — use one style and stick to it
city = "Mumbai"
print(city) # Mumbai
# print(City) ← NameError — it's city, not City
userName = "Alice" then trying to use username later. Python sees them as different variables and throws a NameError. This is why the PEP 8 convention of always using snake_case helps — it eliminates ambiguity.
Python Reserved Keywords
Python has 35 reserved keywords — words with special meanings built
into the language. You cannot use them as variable names. Python 3.10+ added a few new ones
(match, case). Here are all of them:
# See all keywords programmatically
import keyword
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async',
# 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
# 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
# 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
# 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
# Check if something is a keyword
print(keyword.iskeyword("for")) # True
print(keyword.iskeyword("name")) # False — safe to use as variable
# ❌ Using keywords as variable names → SyntaxError
# for = 10 ← SyntaxError: invalid syntax
# class = "A" ← SyntaxError: invalid syntax
# if = True ← SyntaxError: invalid syntax
# ✅ Workaround: add underscore if name clashes
type_ = "admin" # 'type' is a built-in, so use type_
list_ = [1, 2, 3] # 'list' is a built-in, so use list_
Multiline Statements & Blank Lines
Sometimes a single statement is too long for one line. Python gives you two ways to break it across multiple lines, plus conventions for blank lines to make code readable.
# METHOD 1: Backslash continuation ( \ )
total = 100 + \
200 + \
300
print(total) # 600
long_string = "Hello, this is a very " \
"long sentence split across lines."
# METHOD 2: Implicit continuation inside brackets ( ), [ ], { }
# Preferred — cleaner and safer than backslash
result = (100 +
200 +
300)
print(result) # 600
# Long list — split across lines inside [ ]
fruits = [
"apple",
"banana",
"cherry",
"mango",
]
# Long function call — split across lines inside ( )
print(
"Name:", "Alice",
"Age:", 25,
"City:", "Vadodara",
)
# Long dictionary — split across lines inside { }
user = {
"name": "Alice",
"age": 25,
"city": "Vadodara",
}
# Long if condition — use brackets
if (age >= 18 and
is_registered and
has_id_proof):
print("Eligible")
Blank Lines — how to use them (PEP 8)
# 2 blank lines before and after top-level functions / classes
def first_function():
print("first")
def second_function():
print("second")
class MyClass:
# 1 blank line between methods inside a class
def method_one(self):
pass
def method_two(self):
pass
# Inside a function: use blank lines sparingly to group logic
def process_order(order):
# validate
if not order:
return
# calculate total
total = order["price"] * order["qty"]
# send confirmation
print(f"Order total: {total}")
- Indentation is mandatory in Python — 4 spaces per level is the PEP 8 standard. Never mix tabs and spaces.
- Each line is one statement. No semicolons needed. Compound statements end their header
line with a colon
:. - Variables are created with
name = value— no type keyword. Python infers type automatically. - Naming rules: start with a letter or
_, only letters/digits/underscores, no spaces, not a keyword. - Naming convention:
snake_casefor variables/functions,UPPER_CASEfor constants,PascalCasefor classes. - Python is case-sensitive:
age,Age,AGEare three different variables. - Python has 35 reserved keywords — you cannot use them as variable names.
- Use brackets
( ) [ ] { }for clean multiline statements. Backslash\also works but is fragile.
Python throws an IndentationError and refuses to run the code at all. For example,
if you write if True: followed by print("hi") at the same indentation level (not indented), Python will
say IndentationError: expected an indented block after 'if' statement.
Python uses indentation to understand code structure, so it is a hard syntax requirement — not
optional like in most other languages.
These are reserved keywords — words that Python has already claimed with specific
meanings in the language grammar. for means "start a loop", class means "define a class", import means "load a module". If Python allowed you to redefine them
as variables, it would become impossible to tell whether for means
"loop" or "a variable named for". Python protects them to keep the language unambiguous. You'll get a
SyntaxError immediately.
snake_case (all lowercase, words separated by underscores) is used for variables and
functions: user_name, calculate_tax(). PascalCase (each word starts with
capital, no underscores) is used for class names: BankAccount,
UserProfile. UPPER_CASE (all caps with
underscores) is used for constants — values that should never change: MAX_SIZE = 100, API_KEY = "xyz".
These are conventions from PEP 8, not enforced by Python itself — but every professional Python
developer follows them.
The preferred way is implicit continuation inside brackets — wrapping the expression
in parentheses ( ), square brackets [ ], or curly braces { }. Python
automatically allows the statement to continue to the next line inside any open bracket. The
alternative is the backslash \ at the end of the
line, but it's fragile — a trailing space after the backslash silently breaks it. Most Python
developers prefer brackets for safety and readability.
Yes, Python is fully case-sensitive. Two practical examples:
1.
Keywords: True and False are Python's boolean keywords (capital T and F). Writing true or false gives a NameError — Python doesn't recognise them as the boolean
values.
2. Variables: If you define userName = "Alice" and later write print(username), Python throws a NameError because username (all
lowercase) is a completely different, undefined variable. This is a very common beginner bug.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.