Idiomatic Style (PEP 8)
Python has a shared style guide called PEP 8. Following it makes your code read like everyone else's, which is the whole point: code is read far more often than it is written.
The naming conventions are the part you use every day:
- Variables and functions use
snake_case:total_price,send_email. - Constants use
UPPER_SNAKE:MAX_RETRIES = 3. - Classes use
CapWords:ExpenseReport. - Names should describe meaning, not type:
usersbeatsuser_list.
A few more habits that mark code as Pythonic:
total = 0
for price in prices:
total += price
# spaces around operators, no spaces inside brackets
result = (a + b) * 2
items = [1, 2, 3]And prefer clear, direct expressions over clever ones. Compare:
# clunky
if len(names) > 0:
has_names = True
else:
has_names = False
# pythonic
has_names = len(names) > 0You do not need to memorize the whole guide. Internalize the naming rules and the rest follows.
Refactor the math into one clean function. Define MAX_BONUS = 100 as a module-level constant, then write a function final_score(base, bonus) that returns base plus bonus, but caps the total at MAX_BONUS. Use snake_case and a single readable expression or two.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.