Lesson 13/48 ยท ๐Ÿ Your First Python
๐Ÿ Your First PythonLesson 13/48
Phase 1 ยท Your First Python12 min

Comments & Clean Code

Write code your future self will actually understand

Here's a truth most beginners discover the hard way: code is written once but read many times.
You write it. You come back in 3 days. Someone else reads it. Your future self reads it at 11pm trying to fix a bug. Readable code saves hours.
Comments and good naming are how you make code readable.
The # comment
Anything after # on a line is ignored by Python, it's a note for humans only.
Using commentspython
# Calculate 20% tip on a restaurant bill
bill = 85.00
tip_rate = 0.20  # 20% as a decimal

tip = bill * tip_rate     # How much to tip
total = bill + tip        # Total to pay

print(total)  # 102.0
Bad comments explain WHAT. Good comments explain WHY.
```pythonx = x + 1 # add 1 to x โ† useless, obviousx = x + 1 # compensate for zero-indexing โ† useful!`
Don't narrate the code. Explain the reasoning behind it.
Variable names matter as much as comments
Which version is easier to understand?
```python# Version Aa = 85b = 0.2c = a * bd = a + c
# Version Bbill_amount = 85tip_percentage = 0.2tip_amount = bill_amount * tip_percentagetotal_due = bill_amount + tip_amount`
Version B doesn't need a single comment, the names explain everything.
Naming rules for Python variables:
  • Use lowercase with underscores: user_name, total_price
  • Be specific: temperature_celsius not temp not t
  • Avoid single letters except i, j, n in loops
  • Never: data, info, stuff, thing, too vague
  • ๐Ÿค”Quick Check

    Which is the best variable name for storing a user's age?

    Practice Exercises

    0/2 solved
    Exercise 1 of 2easy
    โฑ 00:00

    Name It Better

    The code below uses terrible variable names. Rename every variable to something meaningful, then run it.The program calculates a monthly salary from an hourly rate.
    It should still print the same result: 3200.0
    solution.py
    1 / 2
    Exercise 2 of 2easy
    โฑ 00:00

    Add Meaningful Comments

    Add a comment before each calculation explaining WHY you're doing it (not just what).The code calculates a discounted price. It should print:63.75
    solution.py
    2 / 2
    Solve all 2 exercises to unlock completion