It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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!

  1. 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.

  2. Imagine you’re logging events for a program. Write a function log_event(event) that prints:

    "Event recorded: <event>".
  3. 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