We learnt how to utilize files in Python in the previous article. Our scripts are growing in size as they start to make sense. Longer scripts often indicate more utility, but also greater complexity. To cope with this complexity, we need a methodology, and functions may assist. This Python Functions Tutorial will teach you the definition of functions as well as how to use them. You may use them to develop huge scripts and understand the purpose of each piece of code.
Table of Contents about The ultimate guide on functions is Python Functions Tutorial
Here’s what we are going to cover today:
- What exactly is a function in Python?
- Python Function Terminology
- A function’s scope
- Gaining confidence in the scope
- The Scope of the Problem
- Python Function Parameters
- Best practices for PRO-grammers
- Wrapping it up
Almost every modern programming language includes the concept of functions. This is because functions are essential in programming; you simply cannot write good code without them. Even if you just study them in this python functions course, you’ll be able to apply them to whatever language you choose to learn in the future.
Let us start with a quick definition.
A function is a chunk of code that you can reuse in your script without having to rewrite it.
This isn’t the finest textbook-style definition, but it gets the message through. You will have a firm comprehension of it as soon as you see an example.
As an example
If you know the problem, you will know the need for a solution. Thus, imagine you want to show to the user a message several times during your script. For example, this could be the code to show the message.
As you can see, we have 9 lines of code. If we need to use this message multiple times in a script, we need to write it every time. This makes the script longer, and of course harder to read. Furthermore, what if we decide to change the message at some point in the future? We need to search all occurrences in our script and make the changes here. You can see that this is not the way to go.
…and the solution
What if we can tell the script “Hey, play the message here!” instead of writing it every time? This is exactly what a function does. Take a look at the following code.
You can see that we wrapped our message inside the construct
def show_warning_message():. This is the definition of the function, which takes the name of
show_warning_message. This is user-defined, you can use whatever you want. The keyword def is what tells Python that we are creating a function.
However, if you run the code above nothing will happen. This is because we have just defined the function, we told the script “Whenever I say show_warning_message, do this”. We haven’t said “Ok, now do show_warning_message” just yet.
To execute the code of a function, we simply write its name as below (anywhere in the script).
Here we don’t use the keyword
def, because we are using the function – not defining it. Pay also attention to the brackets at the end of the function, in a minute we will explain why they are here.
After finishing this Python Functions Tutorial, you will be able to work with and grasp functions. As a consequence, you must be conversant with function terminology. This is true for all programming languages, not just Python.
- As seen in the prior example, you create a function by declaring its definition.
- When you want to execute the code of a function anywhere in the script, you call it. The caller is the portion of the script that calls a function.
- The scope determines which variables are accessible to the function (more on that later).
- Functions are another word for subroutines since they execute code at the discretion of the main script.
- A global variable is one that is defined in the main script rather than inside a def construct.
Make sure you grasp these five concepts. They are essential for learning the most appealing part of this Python Functions Tutorial.
As from the terminology, you know that a function can work with variables. In fact, you can define variables inside a function, and you can also use variables from outside the function. Try running the following code.
You will get the message
Hello, your name is Marcus. This is because the function can access the variable
name, which was defined outside the function. You can also define some variables inside the function itself. The following code will give you the same result as the one above.
So far so easy. Well, not quite. In fact, functions doesn’t have full access to global variables.
Accessing global variables
Now instead of showing a message, we want to use a function to modify the name. Thus, we create a script like the one below.
Now, we expect to see that the name changes. We print it the first time, and it is “Marcus”, then we change it. The second time we print it, it should be “Albert”, because we re-assigned the value inside the function. Not so easy: look at the output of this code.
We can see that inside the function the name changed. In fact, the line
I changed the name to: Albert is inside the function, and here the name was Albert. However, changes are not retained after function execution. As a result, the second time we print the name we get Marcus.
When you call a function, a local scope is created. It is a secure environment containing the variables for that function. The variables specified in the function, as well as a clone of all global variables, will be present. You may access, read from, and even edit them inside the function this way, but changes will only be saved in the clone, not the original variable. Of course, after a function has finished running, the clone is erased.
You may call another function from inside another function. Python will clone the variables from the outer function’s scope to the inner function’s scope if you do this. Using an example, we can observe this in action.
With this code, Marcus will get a friendly salutation. The
greet() function will decide to call the
greet_friendly() function after checking the name. We can look at the scope now.
Returns and Parameters
We’ve just used functions as placeholders so far. In actuality, we used them in a way that was similar to copying and pasting their code. We can only use them to display output since they can’t modify their outer scope.
In addition, we have a problem. A function should be self-contained and self-contained from the script. This means we can’t rely on global variables since the function will fail if a global variable’s name changes. Everything must be specified inside the function. So, how do we make use of script variables? Parameters are here to help.
We have a lovely definition for parameters.
Parameters are a feature that allows the caller of the function to initialize some values inside the inner scope of that function.
Take a look at the following function.
Wouldn’t be awesome if we could define the values for
surname outside of the function, but not as global variables? Parameters are just that. You define a tuple of parameters inside the brackets when defining a function. Don’t get confused about tuples, they are just a list of comma-separated values. We can rewrite the function as below.
In this definition, we tell Python that it should expect three values when this function is called. Python will then create the variables
surname inside the scope of the function. At this point, we can initialize their values when calling the function.
This will produce the same output as above. However, now we have control over the initialization of variables inside the scope from outside the function. Awesome.
When first approaching programming, parameters can be tricky. This is why we gave you a good explanation of scopes so that you can understand better how parameters work.
When defining a function, you tell it how many values it should expect, and where to store them inside the scope. We don’t tell what is the name of an outside variable to use. For example, we could do this.
Python will take the content of
variable_3 and put it inside the
title variable in the function’s scope, and so on with the other variables.
With parameters, we can isolate a function from the outer scope. However, we are still limited to output functions that give the results directly to the users. With returns, we can get the results from an elaboration back in our main script. We do that with the
return instruction. When the script reaches that, it stops executing the function and destroy its scope, getting back to its parent scope. While doing that, if you specify a value in the
return, it will give that back to the outer scope.
This is an excellent example. If no numbers are supplied (the list length is 0), we return zero immediately. The function will terminate on that line and return to the outer scope. Instead, if the user gave any numbers, we proceed. We create a sum variable and compute its value by adding all of the integers in the list. At the conclusion of the function, we return the division result: the average.
In the outside script, we take the function’s result value and save it in the result variable. We then print it.
Remember, if your function reaches its end and does not encounter any
return statement, it will implicitly return
Named Parameters and Default Parameters
With that, we covered everything we need to know about functions. However, here we have a few tricks that will help you write code easily.
You can ask the caller of the function to provide all parameters, that’s the default behavior. However, you can also say that some parameters will get a default value if not specified. For example, you can define a function like that:
In this case, we require only to specify one value, that will go into the
name variable. If the user does not provide the
salutation or the
extra_message, we will set them to their default values (“Good Morning” for the salutation and None for the message). We call the parameters with a default value optional parameters. You just need to follow one rule: you cannot have a mandatory parameter after an optional parameter, so specify all the mandatory parameters first.
What if we want to call this function and define the additional message but not the salutation? We can do that with named parameters. Instead of providing a list of parameters, and let the function put the first in the first variable and so on, we can tell what goes where from the caller’s perspective. We use a similar syntax.
Here we tell the value for the message, and we just omit salutation. Even there, remember that the named parameter goes to the right of traditional parameters.
In this Python functions lecture, we examined the foundations of Python functions. At this point, you can build large and intricate code that calls several subroutines. However, by following these recommended practices, you can start producing better code right now. As a general rule, write code that anybody can read and understand. If you need to update your code again in a few months, it should be straightforward to understand. Here are a few suggestions.
- Function names should tell what they do, be all lowercase characters and underscores. However, they shouldn’t start with an underscore.
- A function must be self-contained. Never reference global variables or variables from outer scopes in general. Use parameters!
- Each function must have a clear purpose and do just one thing. Never have something like
average_and_sum, have two separate functions instead. Create functions that you can actually use more than once.
- Don’t hardcode constants in functions unless they truly are constants (like Pi). If you think they may change, even rarely, depending on the outer scope, use optional parameters.
- Comment your function, so that anyone can understand what is its purpose and the way it works.
That brings us to the end of our Python Functions Tutorial. You now have the tools necessary to write efficient code that you can reuse and maintain. I recommend spending a significant amount of time practicing functions since they are the cornerstone of programming. You must understand them before you can construct more complex objects like classes or decorators. What do you think about functions? What plan do you have for them? Please share your thoughts in the comments!
If Our Method Resolve Your Problem Consider To Share This Post, You can help more People Facing This Problem and also, if you want, you can Subscribe at Our Youtube Channel as Well!