iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Syntax

Python's syntax is famously readable. The most distinctive rule: indentation defines blocks. No curly braces, no begin/end.

Indentation = block

PYTHON
if 5 > 2:
    print('Five is greater than two')      # 4 spaces — same block
    print('Still in the if block')
print('Out of the if block')

Pick 4 spaces and stick with it across the whole file. Mixing tabs and spaces is a hard error.

Comments

PYTHON
# Single-line comment

"""
A triple-quoted string used as a block comment.
Technically a string literal, but Python ignores it
when it's not assigned to anything.
"""

Statements end at the newline

No semicolons. To put two statements on one line you'd use a real ; — but almost no Python code does.

Naming

KindConvention
Variables, functionssnake_case
ClassesPascalCase
ConstantsUPPER_SNAKE_CASE
"Private" (by convention)_leading_underscore
Dunder ("magic")__double_underscore__
Tip: Run black on your code. It formats Python to a single canonical style so code reviews never argue about whitespace.

Example

Example
# Indentation defines blocks (4 spaces by convention)
if 5 > 2:
    print('Five is greater than two')
Try it Yourself »

Exercise

Python blocks are defined by…

Answer:

Test yourself

Q1. Python blocks are defined by…
Q2. Most teams use which indent width?
Q3. Statements end with…

Discussion

Loading…