Customizing Functions
Learn to create your own functions for specific tasks.
So far, we have added plenty of functionalities to Edward's world. Be it being able to turn(), move(), perform tasks (place_plant() and remove trash()), communicate (using print() and input()), or even remember stuff (variables!), we have come a long way in learning about Python.
It’s time to improve his world some more. But first, interact with the widget below and then we have a question for you.
Did you find it a bit tiresome or redundant when we had to click the turn button multiple times to turn Edward toward a certain direction?
Wouldn’t it have been easier if we could just tell Edward to turn left or right? Let’s interact with the widget below to see what we mean.
Isn't this much better? We can now easily instruct Edward to turn left or right. But how did we do that?
By creating our own functions!
User-defined functions in Python
So far, we've only used the ready-made functions. We weren’t concerned with how those functions worked or how they were coded. We would only call (use) them whenever we needed them. Built-in functions (input(), print(), int(), etc.) are like standard, ready-to-cook recipes that we already know how to use.
You might think that Python has a built-in (ready-made) function for every situation. But we cannot possibly have a ready-made function to meet every need in the world. Instead, Python lets us create functions of our own that we can then use as required.
It’s time we learn how we can create our own functions.
An analogy for functions
Think of a function as a recipe with ingredients and steps. In Python, a user-defined function has parameters (like ingredients) and instructions (the code inside the function).
Here is the basic structure of a user-defined function:
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. Whatever we write after the colon : as instructions within the body of the function definition, it has to be indented. That’s how Python knows that line 5 in the above example is not part of the function definition (because of its indentation), while lines 2–4 are. The return keyword is used to specify the value that the function should return. This value can then be received in a variable when this function is called from anywhere in the code.
def creates a function, and return gives back a result from the function. 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 user-defined functions in Python.
Creating a user-defined function
Let’s say we create a 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.
Lines 1–4 contain the function definition:
This is like creating the title (name of the function,
add_numbers) and a list of ingredients for your recipe (num1,num2). 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 when it receives any generic inputsnum1andnum2. 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 theadd_numbers()function.
Line 3 is the function body:
These are the steps or instructions to follow that turn the inputs (
num1,num2) into the output (result1andresult2).
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 code reusability is.
Parameters are placeholders for the values a user will pass to the function. Whether a function has input parameters depends on its purpose and the data it needs to perform its task. In the example above, we want to compute the sum of two numbers—hence, the two parameters.
Customizing Edward’s functionalities
Let’s take this use case of turning for Edward. Given that he is facing forward, upon clicking or calling the turn() function, Edward turns right. To make him move left, on the other hand, we have to call or click the turn() function thrice.
Using this information, how about we create our own functions called turn_left() and turn_right()? Go ahead and click the Run button.
Note: We skipped the return statement. We do it when the function's purpose is to simple perform an action and we don't need to compute and return a result or value (e.g., printing a message or turning Edward).
Now, try and implement the turn_left() function.
Now, how about we create a turn_around() function that can help Edward turn around whenever called.
To read more about why we need user-defined functions, read below.
All in all, functions help create modular and reusable code, such as code that displays a standard message, performs calculations, or other predefined tasks.
Understanding the main() function in Python
Now that we know about the user-defined functions, let’s talk about a special kind of function called main().
What is the main() function?
In terms of writing good modular and structured code, it is a good idea to define small helper functions, where each of these does a single unit of work, and then define another function called main(). It’s a function that lets us organize and structure our program. After we’ve written all the function definitions, we write the main logic of our program (sequence of instructions including function calls) inside the main() function.
When we run a Python program, it starts at the top and reads each line. If we want to run a special set of instructions first, we need to put them inside the main() function and then tell Python to run it by calling main() at the end of our program.
Think of main() as a chef in a kitchen who coordinates the preparation of a meal. The chef ensures that all steps (instructions including function calls) come together at the right time to make a delicious dish.
To understand what we mean, let’s look at the example below.
Note that the main() function is actually the starting point of a program. When we run a Python program that has the main() function, this function is executed first followed by the function calls or logic written inside it.
Recap
Key takeaways:
Functions: Functions are a named block of code that perform specific tasks. We use functions for modularity, reusability, and clarity in our code.
The
defkeyword: This keyword is used to define a function. We usedefto tell the computer, “Here is a new function."The
returnkeyword: This keyword is used inside a function to send a value back to the part of the program that called the function. It tells the function, "Give this value back to the caller."Defining a function: This means creating a function and telling the computer what the function should do. We use the
defkeyword to define a function.Calling a function: This means using the function we defined. When we call a function, the computer runs the code inside that function. If we don’t call a function, its function definition will not get executed.
Code reusability with functions: We can define a function once and call it with different arguments in various parts of our program. Defining a function is like writing down a recipe, and calling a function is like following the recipe to make a dish.
The
main()function: Themain()function helps us organize our code and make it easier to understand and manage. It serves as a way to structure our code in a clear and organized manner.What is
main()?: It's the starting point of a program.Why use
main()?: For better organization, readability, and control.How to use
main(): Define your main logic inside themain()function and then call themain()function.
A quick quiz
Consider the following simple Python program structure:
def greet():print("Hello, welcome to the program!")def main():greet()print("This is the main function.")# Main executionif __name__ == "__main__":main()
Describe in words the flow of program execution in this example. Specifically, how does the use of the main() function affect the order in which the code is executed?