Why Code Style Matters
Readable code is easier to debug, grade, and maintain. Examiners don't explicitly award style marks, but clean code is easier to follow โ meaning more partial credit when something goes wrong.
Rule 1: Naming
Variables and Functions: lowercase_with_underscores
# Good
student_name = "Chan"
def calculate_total(items):
...
# Bad
StudentName = "Chan"
def calcTotal(items): # camelCase is for Java/JS
Constants: UPPER_CASE
MAX_STUDENTS = 40 PI = 3.14159
Classes: CapitalizedWords
class StudentRecord:
...
class BankAccount:
...
Rule 2: Indentation
Use 4 spaces. Never tabs. Be consistent.
if x > 0:
print("positive") # 4 spaces
if x > 100:
print("large") # 8 spaces
Rule 3: Spaces Around Operators
# Good x = 5 + 3 if y == 10: a, b = 1, 2 # Bad x=5+3 if y==10: a ,b=1 ,2
Rule 4: Blank Lines
- 2 blank lines between functions
- 1 blank line between logical sections in a function
def function_one():
pass
def function_two():
pass
Rule 5: Line Length
Keep lines under 80 characters. If longer, break them:
# Too long
result = some_function_with_long_name(argument_one, argument_two, argument_three)
# Better
result = some_function_with_long_name(
argument_one,
argument_two,
argument_three
)
Rule 6: Imports
# At top of file, one per line import math import random from datetime import datetime # Not this: import math, random
Rule 7: Comments
Explain why, not what:
# Bad: describes what code says total += 1 # increment total # Good: explains reasoning # Skip header row in CSV next(reader)
Rule 8: Docstrings (Optional)
def calculate_grade(score):
"""Return letter grade from numeric score."""
if score >= 80: return 'A'
...
Rule 9: Avoid Magic Numbers
# Bad
if score >= 50:
print("pass")
# Better
PASS_MARK = 50
if score >= PASS_MARK:
print("pass")
Rule 10: Meaningful Names
# Bad
x = 40
y = []
for a in x:
y.append(a * 2)
# Good
num_students = 40
doubled = []
for n in range(num_students):
doubled.append(n * 2)
Quick Checklist for HKDSE
- โ 4-space indentation (consistent)
- โ Meaningful variable names
- โ Spaces around operators
- โ One statement per line
- โ No trailing whitespace
PyForm Enforces Clean Style
PyForm's Monaco editor auto-indents and highlights style issues โ build good habits from day one.
Open PyForm โ