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
print("Ali is learning Python")
print("He studies every evening")
print(10 + 5)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
marks = 75
if marks >= 50:
print("Pass")
print("Well done!")
print("Result checked")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
marks = 75
if marks >= 50:
print("Pass")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 block | Example |
|---|---|
| if | if age > 18: |
| for | for item in items: |
| while | while count < 5: |
| def | def greet(): |
| class | class Student: |
Python is Case Sensitive
Upper case and lower case letters are different in Python. print works, but Print or PRINT does not.
Example
city = "Karachi"
City = "Lahore"
print(city)
print(City)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
total = (1500 + 2300 +
800 + 450)
print(total)5050
Exercise
Exercise
What does indentation do in Python?
