๐ What is Python syntax?
Syntax is the set of rules that tells Python how to read and execute your code. It's like grammar in English โ without it, the meaning breaks down. Python's syntax is deliberately simple: indentation defines blocks, comments explain intent, and naming conventions make code readable.
Unlike languages with braces {} or semicolons ;, Python uses whitespace to organize code. This forces clean, readable structure. Every rule you'll learn here serves one goal: make code so clear that teammates instantly understand it.
๐ฆ Scenario: Arjun reviews messy code
Arjun works in SouthBank India's backend team in Mumbai. His colleague Priya just sent him a Python script that calculates transaction fees. The code runs, but it's a mess: inconsistent indentation, no comments, cryptic variable names like x and f. Arjun needs to understand it fast before merge, but he's lost.
Today's lesson is exactly what Arjun needs โ the syntax rules that would have saved Priya's (and Arjun's) time. We'll fix Priya's code together, step by step.
โ๏ธ Indentation: Python's block language
Python uses indentation (spaces at the start of a line) to define code blocks โ functions, loops, conditionals, classes. Most Python code uses 4 spaces per level. Never mix tabs and spaces; they cause silent errors.
Bad indentation (Priya's original mistake)
Good indentation (Arjun's fix)
Key rule: 4 spaces per indent level. Tools like VS Code auto-indent โ trust them.
๐ Statements vs expressions
Statements are instructions that *do* something: assign, return, loop, import. Expressions are code that *evaluates* to a value. A statement can contain expressions, but not the other way around.
โก๏ธ Line continuation
Long lines reduce readability. Use a backslash \ or parentheses () to break lines.
๐ Naming conventions: snake_case, PascalCase, CONSTANTS
Python follows PEP 8 naming rules. Good names are clear, not clever. Avoid single letters except in loops.
Reserved keywords: never use as names
These words belong to Python. Using them as variable names causes syntax errors:
if, else, elif, for, while, def, class, return, import, from, as, try, except, finally, with, pass, break, continue, True, False, None, and, or, not, is, in, lambda, yield, assert, del, global, nonlocal.
Good vs bad names
Fixed version:
๐๏ธ PEP 8: Python's style guide
PEP 8 is the official Python Enhancement Proposal for code style. It's not law โ it's a consensus on what readable code looks like. Professional teams follow it.
Key PEP 8 rules
x = 5 not x=5. a + b not a+b.๐ Where syntax matters in real work
pylint and black enforce syntax rules automatically. Bad syntax fails the build.How AI models use syntax
Every time a language model (like Claude) reads Python code, it relies entirely on syntax being correct. Inconsistent indentation confuses the model. Missing comments mean the model guesses intent. Clear naming and docstrings let AI understand your code's purpose instantly.
๐ฏ Your turn: Fix Priya's code
Given messy code, refactor it to follow PEP 8 and add comments:
Fix these issues:
- Inconsistent indentation
- Spaces around operators missing
- Bad variable names (f, r, x, y)
- No comments or docstring
f โ fee_amount, amt โ amount, add if amount > 1000: with spaces. Add a docstring explaining what the function does. Spaces around = and >.
๐ค Interview questions
help() and IDEs. Use triple quotes: """...""".
{} to define blocks. This forces code to be visually structured โ you can't hide a block inside single line. It makes code scannable and prevents bugs. The convention is 4 spaces because it's readable without being wasteful of horizontal space. Most editors auto-indent.
for = 5 will raise a SyntaxError. You can check all reserved words with import keyword; print(keyword.kwlist).
x = 5 is a statement; 5 + 3 is an expression that evaluates to 8. Expressions can be part of statements, but not vice versa.
black can auto-convert: use black --line-length 79 file.py. In VS Code, convert tabs to spaces via the status bar. It's dangerous because indentation errors can hide โ the code runs in one editor but fails in another.
๐ฏ Quiz
๐ Cheatsheet
| Rule | Good | Avoid |
|---|---|---|
| Variable names | transaction_fee |
TransactionFee or f |
| Function names | calculate_fee() |
CalculateFee() or calcFee() |
| Class names | BankAccount |
bank_account or BANKACCOUNT |
| Constants | MAX_FEE_PERCENT |
max_fee_percent or MaxFeePercent |
| Indentation | 4 spaces per level | Tabs or 2/3 spaces |
| Operator spacing | x = 5 + 3 |
x=5+3 or x = 5+ 3 |
| Single comments | # Explain why |
# This is a for loop (obvious) |
| Docstring | """Purpose, Args, Returns""" |
No docstring or # comment instead |
๐จ Common mistakes
class = "BankAccount". Python owns that word. Use class_name = "BankAccount" instead.# add 1 to count. Instead: # retry after delay per SouthBank timeout rule. Comments explain *why*, not *what*.fee = amount * 0.02, not fee=amount*0.02. Spaces improve readability and follow PEP 8.โจ Key takeaways
- Indentation is syntax: Python uses 4-space indentation to define blocks. Never mix tabs and spaces.
- Statements do; expressions are: Statements are actions (assignments, loops). Expressions evaluate to values (math, conditions).
- Comment the why, not the what: Good comments explain intent and design decisions, not obvious syntax.
- Use docstrings for functions: Document what a function does, its arguments, return value, and examples. Tools read docstrings.
- Follow naming rules: Variables and functions are
snake_case. Classes arePascalCase. Constants areSCREAMING_CASE. Never use reserved keywords. - PEP 8 is your friend: Follow it for readability and team consistency. Tools like
blackauto-format your code.
Master Python syntax with live projects
Join the Best AI Program: The AI-Era Analyst โ 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst โ
๐ฌ Comments: Single-line and multi-line
Comments explain *why* code exists, not *what* it does. Good comments answer: "Why did the developer make this choice?" Bad comments state the obvious.
Single-line comments with #
Use
#for one-liners. They narrate logic, not syntax.Multi-line comments with triple quotes
Use triple quotes
"""..."""for longer explanations. These can span multiple lines without repeating#.Docstrings: document your functions
A docstring is a special comment directly after a function/class definition. It documents *what* the function does, *how* to use it, and optionally examples. Tools like IDE hover-tips and the
help()function read docstrings.