Python Tutorial › Getting Started › Python Syntax

Python Syntax

BeginnerLesson 5 of 479 min read9 runnable examples

Syntax is the set of rules for how Python code must be written. Python’s rules are few, but one of them, indentation, is stricter than in most languages. Learn these rules once and most beginner errors disappear.

Advertisement
In this lesson
  • How statements and lines work
  • Why indentation defines blocks
  • How to split long lines
  • Python keywords and case sensitivity

Statements and lines

A Python program is a list of statements, normally one per line. Python runs them from top to bottom. No semicolon is needed at the end of a line.

Python
city = "Pune"temperature = 31print(city, temperature)
Output
Pune 31

Indentation defines blocks

Many languages use curly braces { } to group lines. Python uses indentation: the spaces at the start of a line. A line ending in a colon : starts a block, and every line in that block must be indented by the same amount.

Python
score = 82 if score >= 50:    print("Passed")          # inside the if block    print("Well done")       # also insideprint("Report finished")     # outside: runs every time
Output
Passed
Well done
Report finished
Tip

Use 4 spaces per level. Every IDE inserts 4 spaces when you press Tab in a .py file. Never mix tabs and spaces in one file.

Wrong indentation is a syntax error, and Python refuses to run the file:

Python
if True:print("not indented")
Output
  File "main.py", line 2
    print("not indented")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 1

Indenting a line that should not be indented is also an error:

Python
print("one")    print("two")
Output
  File "main.py", line 2
    print("two")
IndentationError: unexpected indent

Blocks inside blocks

Each new block adds one more level of indentation. Python knows a block has ended when the indentation goes back.

Python
for n in [1, 2, 3, 4]:    if n % 2 == 0:        print(n, "is even")    else:        print(n, "is odd")print("done")
Output
1 is odd
2 is even
3 is odd
4 is even
done

Long lines

Python ends a statement at the end of the line, except inside brackets (), [] or {}. So the easiest way to split a long line is to wrap it in parentheses.

Python
total = (    120    + 80    + 45)names = ["login", "search",         "checkout"]print(total, names)
Output
245 ['login', 'search', 'checkout']

A backslash \ at the end of a line also continues it, but brackets are clearer and are what the PEP 8 style guide recommends.

Several statements on one line

A semicolon lets you put two statements on one line. It works, but it hurts readability, so use it rarely.

Python
a = 1; b = 2; print(a + b)
Output
3

Case sensitivity

Python is case-sensitive: name, Name and NAME are three different variables, and Print is not the same as print.

Python
name = "Asha"Name = "Ravi"print(name, Name)Print("hello")
Output
Asha Ravi
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    Print("hello")
    ^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?

Keywords

Keywords are reserved words with a special meaning, such as if, for and def. You cannot use them as variable names. The keyword module lists them:

Python
import keywordprint(len(keyword.kwlist))print(keyword.kwlist)
Output
35
['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']
Note

True, False and None are keywords too, and they start with a capital letter. true or none would be treated as ordinary (undefined) names.

Check your understanding

Predict the output

x = 5if x > 3:    print("big")print("end")if x > 10:    print("huge")

Quick quiz

1. What marks the start of a block in Python?

2. How many spaces per indentation level does PEP 8 recommend?

3. Which of these is a valid variable name?

Exercise: fix the indentation

This program should print “Even numbers:” once, then each even number, then “Done”. Fix the indentation so it runs.

Hint 1

Only the print(n) line belongs inside the if.

Hint 2

“Done” must print once, after the loop, so it should not be indented.

Program Practice

Python syntax FAQ

Does Python use semicolons?

Not normally. A newline ends a statement. A semicolon is only needed to put two statements on one line, which is rarely a good idea.

What is an IndentationError?

It is the error Python raises when lines in a block are not indented consistently, or when a block is missing after a colon.

Can I use tabs instead of spaces in Python?

Python accepts tabs, but not a mix of tabs and spaces in the same block. Use 4 spaces; every editor can insert them for you.

Is Python case-sensitive?

Yes. total and Total are different names, and built-in functions such as print must be lowercase.

Leave a Comment