๐Ÿ“ 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

๐ŸŽฏ
Real World
SouthBank India โ€” Code Review in Mumbai

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.

โ‚น500
Avg Transaction
2%
Fee Rate
3
Code Issues

โš™๏ธ 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)

โŒ Inconsistent indentation
Error
IndentationError: unexpected indent

Good indentation (Arjun's fix)

โœ“ Consistent 4-space blocks

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.

Statement
x = 10
Assigns a value. Ends the line.
Expression
10 + 5
Evaluates to 15. Can be used in statements.
Statement
if x > 0: pass
Control flow. Must end with a colon.
Expression
x if x > 0 else 0
Ternary operator. Returns a value.

โžก๏ธ Line continuation

Long lines reduce readability. Use a backslash \ or parentheses () to break lines.

โœ“ Line continuation with backslash

๐Ÿ’ฌ 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.

โœ“ Good single-line comments

Multi-line comments with triple quotes

Use triple quotes """...""" for longer explanations. These can span multiple lines without repeating #.

โœ“ Multi-line comment block

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.

โœ“ Function with docstring

๐Ÿ“ Naming conventions: snake_case, PascalCase, CONSTANTS

Python follows PEP 8 naming rules. Good names are clear, not clever. Avoid single letters except in loops.

snake_case
transaction_fee
Variables & functions. Lowercase, underscores.
PascalCase
BankAccount
Classes. First letter capital, no underscores.
SCREAMING_CASE
MAX_FEE_PERCENT
Constants. All caps, underscores.
_private
_internal_id
Private (not for external use).

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

โŒ Bad names (Priya's original code)

Fixed version:

โœ“ Good names (Arjun's refactor)

๐Ÿ—๏ธ 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

๐Ÿ“
Max line length
79 characters for code, 72 for docstrings. Break long lines.
๐Ÿ”ค
Two blank lines
Between top-level functions and classes. One blank line between methods.
๐Ÿ“
Spaces around operators
x = 5 not x=5. a + b not a+b.
โฌœ
Indentation = 4 spaces
Never tabs. Never 2 or 3 spaces. Always 4.

๐ŸŒ Where syntax matters in real work

๐Ÿฆ
Banking & fintech
Code reviews catch syntax errors before they cost โ‚น50,000. Clean syntax = trust.
๐Ÿ“Š
Data science teams
Jupyter notebooks require clean syntax. Teammates must read 500-line data pipelines. PEP 8 saves time.
๐Ÿค–
ML/AI workflows
LLMs like Claude parse clean Python far better than messy code. Docstrings help explain intent to AI training.
๐Ÿ”
DevOps & CI/CD
Linters like 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.

Indentation Comments Docstrings Naming PEP 8

๐ŸŽฏ Your turn: Fix Priya's code

Given messy code, refactor it to follow PEP 8 and add comments:

Messy code

Fix these issues:

  • Inconsistent indentation
  • Spaces around operators missing
  • Bad variable names (f, r, x, y)
  • No comments or docstring
Hint: Use 4 spaces, rename f โ†’ fee_amount, amt โ†’ amount, add if amount > 1000: with spaces. Add a docstring explaining what the function does. Spaces around = and >.

๐ŸŽค Interview questions

A docstring is a string literal that appears right after a function, class, or module definition. It documents what the code does. Unlike comments (which start with #), docstrings are part of the object and can be read by tools like help() and IDEs. Use triple quotes: """...""".
Python uses indentation instead of braces {} 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.
No. These are reserved keywords in Python. The interpreter has special behavior for them. Using for = 5 will raise a SyntaxError. You can check all reserved words with import keyword; print(keyword.kwlist).
A statement is an instruction (assignment, loop, function call) that performs an action. An expression evaluates to a value and can be used in other contexts. For example, x = 5 is a statement; 5 + 3 is an expression that evaluates to 8. Expressions can be part of statements, but not vice versa.
Tabs and spaces look similar but have different byte values. Python defaults to treating tabs as 8 spaces, which can cause unexpected indentation. Your editor or a tool like 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

Question 1 of 5
What is the correct way to write a variable name in Python?
Question 2 of 5
How many spaces should you use for indentation in Python?
Question 3 of 5
What symbol starts a single-line comment in Python?
Question 4 of 5
Which of these is a reserved keyword and cannot be used as a variable name?
Question 5 of 5
What is a docstring used for?
5
/ 5
Perfect! ๐ŸŽ‰

๐Ÿ“‹ 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

Mixing tabs and spaces
Python sees them as different lengths. Always use 4 spaces. In VS Code, set "Use Spaces" in the status bar.
Using reserved keywords as names
Don't do class = "BankAccount". Python owns that word. Use class_name = "BankAccount" instead.
Writing obvious comments
Skip # add 1 to count. Instead: # retry after delay per SouthBank timeout rule. Comments explain *why*, not *what*.
Skipping spaces around operators
Write 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 are PascalCase. Constants are SCREAMING_CASE. Never use reserved keywords.
  • PEP 8 is your friend: Follow it for readability and team consistency. Tools like black auto-format your code.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’