Using Functions to Simplify Code
Why Simplify?
When writing code, you'll often repeat the same set of instructions. Instead of copying and pasting, it's cleaner and smarter to wrap that logic in a function.
This not only makes your code easier to read and maintain, but it also reduces the chances of making mistakes.
Without Functions
Here's a program that prints a greeting to multiple users without using functions:
print("Hi Ama!")
print("Welcome to LanceCourse!")
print("Hi Kofi!")
print("Welcome to LanceCourse!")
print("Hi Abena!")
print("Welcome to LanceCourse!")
This works, but imagine greeting 1,000 users!! The code becomes repetitive and harder to manage.
With Functions
Let’s refactor the above using a function:
def greet_user(name):
print("Hi", name + "!")
print("Welcome to LanceCourse!")
greet_user("Ama")
greet_user("Kofi")
greet_user("Abena")
Same result, but way more efficient, reusable, and readable!
If you find yourself copying and pasting similar blocks of code, that’s a good sign it’s time to use a function.
Exercise: Try It Yourself!
-
Write a function called
show_course(course_name)
that prints something like:Welcome to <course_name> You’re going to learn amazing stuff!
Call it with different course names.
-
Imagine you’re logging events for a program. Write a function
log_event(event)
that prints:"Event recorded: <event>".
-
Refactor the following code into a function:
print("Calculating results...") print("Done!") print("Ready to proceed.")
Name the function process_complete()
and call it.
Summary
- Functions simplify code by reducing repetition.
- You can call the same function with different values (parameters).
- Cleaner code = happier coder