A song sheet
The chorus is written once. Then the sheet just says "Chorus" again.
11CLEAN CODE · DON'T REPEAT
When lines repeat, a loop or a function can do the work: same output, shorter and safer code.
IN REAL LIFE
People find smart ways to avoid doing the same work twice.
The chorus is written once. Then the sheet just says "Chorus" again.
She doesn't draw each star by hand. One stamp makes the same star every time.
"Repeat for each pancake" instead of writing the steps ten times.
LOOK FIRST
Three print("Hooray!") lines become one for loop with range(3).
When only a name changes, write a function with a parameter for it.
The lines live in one spot. Change them once and every use changes.
LOOK FIRST
Two welcomes, but the lines are written only once.
def welcome(name):One function. The parameter name is the part that changes. print("Hi, " + name + "!")Written once, used for everyone. print("Welcome to the team.")Change this line once, and every welcome changes.welcome("Ana")Runs both lines with name = "Ana".welcome("Leo")The same lines again, now for Leo.RUN IT
Guess first. Then run real Python and check.
def cheer(name):
print("Go, " + name + "!")
for friend in ["Ana", "Leo", "Mia"]:
cheer(friend)What will Python show?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change "Go, " to "Yay, " in one place and run. All three lines change!
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
What is the cleanest song sheet?
print("Brush teeth")
print("Brush teeth")
print("Brush teeth")Which cleaner code shows the same output?
for i in range(4):
print("Jump!")
print("Rest")How many repeated print lines does this loop replace?
print("Happy birthday, Ana!")
print("Happy birthday, Leo!")
print("Happy birthday, Mia!")What is the best tool to clean this up?
def birthday(name):
print("Happy birthday, " + name + "!")
birthday("Leo")What will Python show?
How many places do you edit?
So why clean it?
PyBot changed the snack from cookies to apples, but missed one copy. Write a function so the snack lives in one place, and match the goal.
Ana gets an apple. Thanks, PyBot! Leo gets an apple. Thanks, PyBot! Mia gets an apple. Thanks, PyBot!OUTPUT
Want a fresh start? Clear only this page.
Repeated lines become a loop. Repeated chunks with small changes become a function with a parameter. Then one fix fixes everything.