Python Syntax

Python · Lesson 3 of 56 6 min read Updated

Every language has grammar rules. In English, a sentence starts with a capital letter and ends with a full stop. In Python, the rules are about lines, colons and indentation. These rules are called syntax, and Python is strict about them: if the syntax is wrong, the program does not run at all.

In this lesson you will learn the handful of rules that every Python file follows, and how to read the error messages Python shows when a rule is broken.

One statement per line

A statement is one instruction, such as "store this value" or "print this text". In Python, each statement normally sits on its own line, and Python runs the lines from top to bottom.

PythonRun it yourself
train = "Shatabdi Express"
seats_left = 42
print(train)
print("Seats left:", seats_left)
Output
Shatabdi Express
Seats left: 42

There is no semicolon at the end of each line, unlike Java, C or JavaScript. You can put two statements on one line with a semicolon between them, but almost nobody does, because it makes code harder to read.

Indentation makes blocks

Some statements own a group of lines, called a block. For example, an if statement owns the lines that should run only when its condition is true. In Python you show this in two steps:

  1. End the first line with a colon :.
  2. Indent every line of the block by the same amount, normally 4 spaces.
PythonRun it yourself
marks = 72

if marks >= 40:
    print("Result: Pass")
    print("Well done, Kabir!")

print("Report printed")
Output
Result: Pass
Well done, Kabir!
Report printed

The two indented lines belong to the if block. The last line is back at the left edge, so it is outside the block and always runs. Change marks to 30 and run it again: only "Report printed" appears.

Many languages use curly braces {} for blocks and treat indentation as decoration. In Python, indentation is the structure. That is why Python code from different people tends to look neat and similar.

Comments

A comment is a note for humans. Python ignores everything after a # on a line. Use comments to explain why the code does something, not to repeat what it obviously does.

PythonRun it yourself
# Ticket price for the Jaipur city bus
fare = 25

# Students get 40% off, so they pay 60% of the fare
student_fare = fare * 0.6

print(student_fare)  # 15.0
Output
15.0

Python has no special syntax for multi-line comments. Put a # at the start of each line. You will also see text in triple quotes at the top of functions; those are docstrings, which describe what a function does, and you will meet them in Functions.

Python is case-sensitive

city, City and CITY are three different names in Python. Keywords such as if, for and True must be written exactly as Python expects.

Python
city = "Pune"
print(City)

Running this stops with an error. The last line of the message says:

Text
NameError: name 'City' is not defined. Did you mean: 'city'?

Modern Python error messages often suggest a fix, as this one does. Always read the last line of an error first: it names the problem.

Long lines

Very long lines are hard to read. If a line is inside brackets (), [] or {}, you can break it over several lines and Python joins them for you:

PythonRun it yourself
total = (
    1299   # school bag
    + 450  # water bottle
    + 899  # shoes
)
print("Total: ₹", total)
Output
Total: ₹ 2648

You may see a backslash \ at the end of a line in older code to continue it. It works, but brackets are clearer and safer, so prefer them.

Python style in short

The Python community follows a style guide called PEP 8. The main points for now:

  • Indent with 4 spaces.
  • Use lowercase names with underscores for variables, such as seats_left.
  • Put spaces around = and operators: total = price + tax.
  • Keep lines reasonably short (PEP 8 suggests 79 characters).

Tools called formatters, such as Black and Ruff, can tidy your code to this style automatically.

Common mistakes

  • Forgetting the colon. if marks >= 40 without : gives SyntaxError: expected ':'.
  • Forgetting to indent. A line right after if ...: that is not indented gives IndentationError: expected an indented block after 'if' statement.
  • Indenting for no reason. A line indented more than the line before it, when no colon came first, gives IndentationError: unexpected indent.
  • Mixing tabs and spaces. This gives TabError: inconsistent use of tabs and spaces in indentation.
  • Curly quotes copied from a document. Text pasted from Word or a chat app may contain “smart quotes”. Python only accepts straight quotes " and ', and reports SyntaxError: invalid character.

Key points

  • Each statement goes on its own line, and Python runs the lines from top to bottom.
  • A line ending in : starts a block; the block's lines are indented by 4 spaces.
  • # starts a comment, which Python ignores.
  • Names are case-sensitive: city and City are different.
  • Break long lines inside brackets instead of using a backslash.
  • Read the last line of an error message first; it tells you what went wrong.

Exercise

This program has three syntax mistakes. Find and fix them so it prints both lines when age is 18 or more.

Python
age = 19
if age >= 18
print("You can vote in India")
    Print("Remember your voter ID")
Show solution
Python
age = 19
if age >= 18:
    print("You can vote in India")
    print("Remember your voter ID")

The if line needed a colon, both lines of the block needed the same 4-space indent, and Print had to be lowercase print.

Quick Quiz

1. What must come at the end of an if line in Python?

2. How does Python know which lines belong to a block?

3. What does Python do with text after # on a line?

4. Which name is different from total?

Learn Python with a mentor

Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call