User-Defined Functions
Learn how to make your own functions.
We know that built-in functions (input(), print(), int(), etc.) are like standard ready-to-cook recipes everyone knows how to use. But did you know we can create our own functions as well? We cannot possibly have a ready-made function against every need in the world. Imagine if we wanted to create YouTube, and there was a built-in function BuildYouTubeForMe("please")? It doesn’t work like that, right? Instead, Python lets us create functions of our own that we can then use as and whenever required, just like we can use built-in functions.
All in all, functions help create modular and reusable code, such as displaying a standard message, generating random numbers, or performing other predefined tasks.
What are user-defined functions?
Here is the basic structure of a function:
def function_name(parameter1, parameter2):# Function body# ...return result
We use the def keyword to define the function, followed by the function name and a set of parentheses. The parentheses () may contain parameters, and a colon : at the end of the line that indicates the start of the function body. The return keyword is used to specify the value that the function should return.
You don’t have to be intimidated by any of it, we’ll cover all the basic keywords (like def and return ) and concepts needed to understand the user-defined functions in Python.
An analogy for functions
A recipe has ingredients and a set of steps. In Python, a user-defined function has parameters (like ingredients) and a set of instructions (the code inside the function).
Lines 1–4 contain the function definition:
This is like creating the title (name of the function,
order_pizza) and a list of ingredients for your recipe (pizza_type, extra_topping). When we define a function, we are creating a reusable block of code with a specific purpose. This is an abstract representation of what the function does. It’s like creating a blueprint or a recipe for a certain task without actually executing it. Notice the extra spaces or indentation at the start of lines 2–4, that’s how Python knows what part of your code is part of theorder_pizzafunction.
Line 3 is the function body:
These are the steps or instructions to follow that turn the inputs (
pizza_type, extra_topping) into the output (pizza).
Lines 7 and 10 are the function calls made to our own function that we defined earlier:
This is like using our recipe to make a specific dish. When we call a function, we provide actual values (arguments) for the parameters defined in the function. The function then executes using these specific values. Notice how we used the same function call to give us two different pizzas. This is what the reusability of code means.
Creating a user-defined function
Let’s define another user-defined function, add_numbers that returns the sum of num1 and num2. Run it once to see if the function is working as expected.
The above function should run fine, we even called the function (line 7). But why couldn’t we see the result? You guessed it, we haven’t printed the result yet!
Go ahead and add the print statement in the code above.
Using user-defined functions in our project
To understand how these user-defined functions help make our code more readable and clearer, let’s look at our project’s code below.
A code without functions
n1 = 6
n2 = 7
question = "What is " + str(n1) + "+" + str(n2) + "? Ans: "
user_answer = input(question)
print("Your answer is:", user_answer)
# Compute the correct answer
print("The correct answer is:", n1 + n2)
question = "What is " + str(n1) + "-" + str(n2) + "? Ans: "
user_answer = input(question)
print("Your answer is:", user_answer)
# Compute the correct answer
print("The correct answer is:", n1 - n2)
question = "What is " + str(n1) + "*" + str(n2) + "? Ans: "
user_answer = input(question)
print("Your answer is:", user_answer)
# Compute the correct answer
print("The correct answer is:", n1 * n2)
question = "What is " + str(n1) + "/" + str(n2) + "? Ans: "
user_answer = input(question)
print("Your answer is:", user_answer)
# Compute the correct answer
print("The correct answer is:", int(n1 / n2))When writing lines 4, 10, 16, and 22, we are more likely to make a mistake. For example, we could miss a + character, or fail to convert the integer to a string by mistake. It’s way more convenient and safe if we make a function to create a question and use that wherever we need it.
Also, note how the lines of code, to print the expected and the actual answers, are repeating. So, they can be made into a function. Look at the code below to see what we mean.
A code with functions
Notice how the code below is now cleaner and more readable because we defined two helper functions.
def print_question(num1, op, num2): # Function definition to print question
print() # To add a new line for output's readability
question = "What is " + str(num1) + op + str(num2) + "?"
print(question)
def answer_feedback(user_ans, correct_ans): # Function definition to print answer feedback
print("Your answer is:", user_ans)
print("The correct answer is:", correct_ans)
n1 = 6
n2 = 7
print_question(n1, "+", n2) #Function call with definite arguments
user_answer = input("Ans: ")
correct_answer = n1 + n2
answer_feedback(user_answer, correct_answer)
print_question(n1, "-", n2)
user_answer = input("Ans: ")
correct_answer = n1 - n2
answer_feedback(user_answer, correct_answer)
print_question(n1, "*", n2)
user_answer = input("Ans: ")
correct_answer = n1 * n2
answer_feedback(user_answer, correct_answer)
print_question(n1, "/", n2)
user_answer = input("Ans: ")
correct_answer = int(n1 / n2)
answer_feedback(user_answer, correct_answer)Note: There's a difference between defining a function in abstraction and calling the function with definite arguments. We can define a function once and call it with different arguments in various parts of our program.
Review of the lesson
We have seen the power of user-defined functions and how they promote modularity, reusability, and clarity in our code. However, we should always be mindful of the rules of the language and use the proper format, or else our program might result in errors.