Clean Code in Python: Habits Every Beginner Needs
One Statement per Line
Clean code is code that's easy to read, easy to change and hard to get wrong. The first clean-code habit is the simplest: write one statement per line. A statement is one complete instruction, like total = 0 or print(total).
Think of it like a shopping list. One item per line, and you can tick them off one by one. Write everything on one line, and you skip something.
The rules
- Don't squeeze several statements onto one line with semicolons
;. - Don't put the block of an
if,for,whileordefon the same line as its colon. Start a new, indented line. - Compare a
True/Falsevalue directly: writeif is_open:, notif is_open == True:(chapter 8).
Avoid: squeezed lines
a = 3; b = 4; print(a * b)
if a < b: print("a is smaller")12 a is smaller
Python allows both, but you have to read every character to find where one instruction ends. And it can break: an if can't come after a semicolon at all.
marks = 72; if marks >= 40: print("Pass")SyntaxError: invalid syntax
Good: one line, one job
marks = 72
if marks >= 40:
print("Pass")Pass
Now your eye goes straight down the left edge: store, check, print. When an error happens, the line number points to exactly one instruction, so you know where to look.
Common beginner doubt: "Isn't shorter code better?" Fewer lines isn't the goal. Fewer ideas per line is. A program with 10 clear lines beats one with 3 crowded lines.
One statement per line, and every block on its own indented lines.
Comments That Explain Why
A good comment explains why the code does something. The code itself already shows what it does. You learned this in chapter 6. PEP 8 adds a few rules about how comments should look.
Think of it like a note on the fridge. "Milk" says what. "Buy oat milk, Lucky can't drink cow's milk" says why, and that's the part you'd never guess.
PEP 8 rules for comments
## shop closes at 9#shop closes at 9total = 0 # resettotal = 0 # reset# members pay less# subtract 20def.Avoid: comments that repeat the code
Every comment says what the code already says. They add reading, not understanding. Delete them, or say why.
Common beginner doubt: "More comments are always better, right?" No. With clear names (the Naming topic) and small functions, most lines need no comment at all. Save comments for the surprises.