Python Syntax
Python's syntax is minimal but precise. The indentation rule, colons, and f-strings are the three things you must internalise completely.
Indentation is Syntax
Every code block in Python — if statements, loops, functions, classes — is defined by indentation, not braces. The standard is 4 spaces per level. Mixing tabs and spaces causes an IndentationError; inconsistent indentation causes silent logic errors where the wrong code runs inside the wrong block.
mark = 74
# Correct indentation:
if mark >= 50:
print("You passed.") # 4 spaces
print("Well done.") # same level — both inside the if
else:
print("Not yet competent.") # back to same level as if
print("Outside the if.") # zero indentation — always runs
# WRONG — this is a logic error (not a syntax error):
# if mark >= 50:
# print("You passed.")
# print("This runs regardless!") # IndentationError or wrong logic
The Colon
Every control structure header ends with a colon: if, elif, else, for, while, def, class. Forgetting the colon is one of the most common SyntaxErrors.
# All of these require a colon at the end of the header:
if True:
pass
for i in range(5):
pass
while False:
pass
def my_function():
pass
class MyClass:
pass
f-strings
f-strings (formatted string literals) are the modern, preferred way to embed variables and expressions in strings. They are more readable than concatenation and faster than .format().
name = "Thandi"
age = 21
mark = 74.5
course = "Python"
# f-string — prefix with f, embed expressions in {}:
print(f"Hello, {name}. You are {age} years old.")
print(f"Studying {course.upper()} with a mark of {mark:.1f}%")
print(f"In 5 years you will be {age + 5}.") # expressions work too
# Alignment and formatting:
for i, n in enumerate(["Java","C#","Python","SQL"], 1):
print(f"{i}. {n:<10} — available at Your IT Tutor")
# Multi-line f-string:
report = (
f"Learner: {name}\n"
f"Course: {course}\n"
f"Mark: {mark:.1f}%\n"
)
print(report)
Comments
# Single-line comment
"""
Multi-line string used as a comment.
When at the start of a function or class, it is a docstring.
"""
def greet(name):
"""Return a greeting for the given name."""
return f"Sawubona, {name}!"
Practice Task
Your Turn
Write a script with your name, age, city as variables. Use if/elif/else (with colons and correct indentation) to print different messages for age under 20, 20-25, and over 25. Use f-strings for all output. Add a comment explaining each section.
Common Mistakes
- Mixing tabs and spaces — use 4 spaces everywhere, never tabs.
- Forgetting the colon after if, for, def, class.
- Wrong indentation level — code runs in the wrong block silently.
==for comparison,=for assignment — same as Java/C#.
Professional Tip
Set your editor to display whitespace characters so you can see exactly what is a space and what is a tab. VS Code does this with View → Render Whitespace.
Mini Quiz
What is the modern preferred way to embed variables in Python strings?