Why Functions Help
Unit ID: M05-U00 Estimated active time: 18-25 minutes
Repetition creates maintenance risk
Imagine cleaning three course names:
first_name = raw_first_name.strip().title().replace("Ai", "AI")
second_name = raw_second_name.strip().title().replace("Ai", "AI")
third_name = raw_third_name.strip().title().replace("Ai", "AI")
The rule is repeated. If it changes, every copy must change correctly.
A function gives the rule one name:
def clean_course_name(raw_name):
return raw_name.strip().title().replace("Ai", "AI")
Use it with different values:
first_name = clean_course_name(raw_first_name)
second_name = clean_course_name(raw_second_name)
third_name = clean_course_name(raw_third_name)
A function should have one clear responsibility
clean_course_name() cleans a course name. It does not also calculate duration, print a report, modify a file, and install a package.
Small responsibility does not mean one line at all costs. It means the function has one understandable reason to change.
Define before calling
Python must execute the function definition before a call in the current session. In a notebook, hidden state can make an old definition remain active. After editing a function, rerun its definition and dependent cells, then finish with restart-and-run-all.
A function call is an expression
If a function returns a value, its call can be assigned:
clean_name = clean_course_name(" python foundations for ai ")
print(clean_name)
Output:
Python Foundations For AI
When not to create a function
Do not extract every single line automatically. A function helps when it:
- removes meaningful repetition;
- names an important operation;
- separates responsibilities;
- makes focused checking easier; or
- hides a stable implementation behind a clear contract.
Practice
Read a long notebook cell and mark which lines belong to input cleaning, calculation, and display. Propose three function names without writing the functions yet.
Takeaway
Functions name reusable responsibilities and reduce repeated logic. Next, we will define the information a function receives through parameters and arguments.
