Python Tutorial menu

Python Syntax

Syntax means the rules for writing code that Python can understand.

One Statement Per Line

A statement is one instruction. In Python, you normally write one statement on each line. You do not need a semicolon at the end.

Example

python
print("Ali is learning Python")
print("He studies every evening")
print(10 + 5)
Output
Ali is learning Python
He studies every evening
15

Python runs the lines from top to bottom, in order.

Indentation

Indentation means the spaces at the start of a line. Many languages use indentation only to make code look neat. In Python, indentation is part of the rules. It shows which lines belong together in a block.

Example

python
marks = 75
if marks >= 50:
    print("Pass")
    print("Well done!")
print("Result checked")
Output
Pass
Well done!
Result checked

The two indented lines belong to the if. They run only when the condition is true. The last line is not indented, so it always runs.

Indentation Errors

If you forget the indentation, Python stops with an error:

Example

python
marks = 75
if marks >= 50:
print("Pass")
Output
IndentationError: expected an indented block after 'if' statement on line 2

Inside one block, every line must have the same number of spaces.

The standard is 4 spaces for each level. Most code editors insert 4 spaces automatically when you press Tab.

Lines That End With a Colon

A line that starts a block always ends with a colon :. You will see this with if, for, while, def and class.

Line that starts a blockExample
ifif age > 18:
forfor item in items:
whilewhile count < 5:
defdef greet():
classclass Student:

Python is Case Sensitive

Upper case and lower case letters are different in Python. print works, but Print or PRINT does not.

Example

python
city = "Karachi"
City = "Lahore"
print(city)
print(City)
Output
Karachi
Lahore

city and City are two different names.

Long Lines

If a line becomes very long, you can break it inside brackets. Python knows the statement continues until the bracket closes:

Example

python
total = (1500 + 2300 +
         800 + 450)
print(total)
Output
5050

Exercise

Exercise

What does indentation do in Python?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp