Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Syntax

Syntax is the set of rules that says how code must be written, just as grammar says how sentences are written. Python's rules are few, and most of them exist to make code easy to read. The most important one, and the one that surprises people who know other languages, is that indentation matters.

One statement per line

A statement is one instruction: print something, give a variable a value, call a function. In Python you normally write one statement on each line, and the end of the line ends the statement. No semicolon is needed:

print("first line")
x = 5
print("x is", x)
Output
first line
x is 5

Indentation makes blocks

Some statements, such as if, for, while and def, control a group of other statements, called a block. The controlling line ends with a colon, and the lines of the block are indented: they start further to the right, usually by 4 spaces. The block ends where the indentation goes back:

temperature = 31
if temperature > 30:
    print("It is hot today.")
    print("Drink some water.")
print("This line always runs.")
Output
It is hot today.
Drink some water.
This line always runs.

The two indented lines belong to the if; the last line does not. Other languages use curly brackets for blocks and indentation only for looks. In Python the indentation is the structure, so it must be consistent: every line of a block starts at the same column. If it does not, Python stops with an IndentationError. Use spaces, not tabs, and four spaces per level; the editor indents for you when you press Enter after a colon.

Case sensitivity

Python is case-sensitive: name, Name and NAME are three different names. The same goes for keywords and functions: print works, but Print is unknown and gives a NameError. Keywords such as if, for, True and None must be written exactly as they are.

Long lines

A statement can continue on the next line while a bracket is still open. This is the usual way to break a long line:

total = (100 + 250 +
         300 + 50)
print(total)
Output
700

Practice exercises

  1. Write an if block with three indented lines, then a line that is not indented. Run it with a value that makes the condition true, then false.
  2. Indent one line of the block by 2 spaces instead of 4 and read the error.
  3. Write Print("hi") with a capital P and read the error and the hint.
  4. Split a long sum over three lines using brackets.