CodeMIRAI
0 XP

Syntax and indentation

2 min read 5 runnable examples Quiz included

Syntax is the set of rules for how code must be written. Python's rules are simpler than most languages, but there is one you must learn on day one: indentation matters.

One statement per line

Each line is usually one instruction. Python reads them in order from top to bottom.

Python
x = 10
y = 3
print(x + y)

Indentation creates blocks

Many languages use curly braces { } to group lines together. Python uses indentation: the spaces at the start of a line. Lines indented under a statement ending in a colon : belong to it.

Python
temperature = 31

if temperature > 30:
    print("It's hot today.")
    print("Drink some water.")

print("This line always runs.")

The two indented lines only run if the temperature is over 30. The last line is not indented, so it is outside the if and always runs. Change 31 to 20 and run it again to see the difference.

Getting indentation wrong

If you indent inconsistently, Python stops before running anything and tells you where:

Python
if True:
    print("four spaces")
      print("six spaces")

The fix is to use the same indentation for every line in a block. The convention is 4 spaces per level; the CodeMIRAI editor inserts 4 spaces when you press Tab.

Case sensitivity

Python is case-sensitive: name, Name and NAME are three different things. Built-in functions are lowercase, so Print("hi") is an error.

Python
message = "lowercase works"
print(message)
print(Message)

Long lines

A line can be as long as you like, but readable code keeps lines short. Inside brackets, you can break a line freely:

Python
total = (100 +
         250 +
         75)
print(total)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.