Lesson 4 +10 XP

Python Syntax

Python Syntax

Python's rules for writing code are famously simple. Indentation does a lot of the work that other languages use curly braces for.

No semicolons or braces needed

In languages like C++ you end lines with ; and group code with { }. In Python, the indentation groups the code.

if 5 > 2:
    print("Five is greater than two!")

The indented line is part of the if. The colon : announces a block is coming.

Indentation matters

Python uses spaces (or tabs) at the start of a line to show which block a line belongs to. The indented lines below all belong to the if:

if 5 > 2:
    print("One")
    print("Two")
print("Outside the if")

"Outside the if" prints no matter what, because it is not indented.

Keep it consistent

  • Use the same number of spaces for each level. The Python style guide recommends 4 spaces.
  • Never mix tabs and spaces for the same block.
  • If you forget, Python raises an IndentationError.

Case matters

Python is case-sensitive: print, Print, and PRINT are three different words.

print("Hello")  # works
Print("Hello")  # NameError: name 'Print' is not defined

Comments and variables

  • # starts a comment, a note the computer ignores.
  • Variables hold values, assigned with =:
x = 5
name = "Ada"

TL;DR

  • Indentation groups code; the colon starts a block.
  • Always use consistent spaces (4 is the norm).
  • Python is case-sensitive.
  • # makes a comment, = assigns a variable.