Functions in Python
Function in Python: meansMethodsorFunctionsIn the English language, it is a group of commands gathered in one place and executed when we call it.
In addition, Python contains a very large set of ready-made functions, some of which we have already used, such as functions print(), min(), max()and other functions that we discussed in previous lessons.
Next lesson: Working with modules in Python .
Previous lesson: dict class in Python .
terms in functions
Prefab functions in Python are calledBuilt-in Functions.
Functions that the programmer defines are calledUser-defined Functions.
How to define new functions in Python

The basic form to follow when defining a function in Python is the following:
function_suite
• def : you define a new function.
• functionname : we put in its place the name we give the function, through which we can call it.
• () : inside the parentheses you can put parameters, and you should put :them immediately after the parentheses and then go down on a new line to start typing the commands that will be executed when the function is called.
• function_suite : means the commands that we will put in the function and that will be executed when it is called.
Whatch out
You are forced to put 4 blank spaces before the commands you are going to put into the function so that the Python interpreter knows that these commands are inside the function.
To arrange and write the code as other programmers do, add two blank lines after defining the function.
In the following example, we have defined a function named my_functionand placed only one print command in it. Then we summoned her.
first example
# my_function Here we have defined a function whose name is
def my_function():
print('My first function is called')
# In order to execute the command placed in it my_function here we called the function
my_function()
• We will get the following result when running.
All the information that can be given when defining a new function
A little while ago we talked about the basic things that must be available when defining any function.
Now, you need to know that you can put more details provided that you add them in a specific order and not a requirement that you add them all.
""" function_docstring """
function_suite
return [expression]
• def : you define a new function.
• functionname : we put in its place the name we give the function, through which we can call it.
• parameters : they mean the parameters that we pass to them when they are called(Parameter setting is optional).
• ""function_docstring"" : We put in its place a text whose purpose is to briefly explain what the function does(Explanation mode is optional).
• function_suite : means the commands we put in the function.
• return [expression] : We put in its place what the function can return in the place from which it was called(Returning a value is optional).
Here we have defined a function whose name is called greeting. When called, we pass a name to it, and it prints a welcome message for the name that was passed to it.
second example
# Contains one parameter. When called, we pass it a name, and it prints a sentence with the name of the person we pass it on. Here we have defined its name function.
def greeting(name):
"" This function print hello message based on the specified name ""
print('Hello '+name+', welcome to our company.')
# user Here we have stored the name of the person we are going to pass to the function in the variable
user = 'Ahmad'
# To print a welcome message for the user and pass the name of the person we have stored in the variable greeting() here we called the function
greeting(user)
• We will get the following result when running.
Here we have written the same function as the previous one, but this time we have printed the explanation in the function(i.e. thedoc string)And not summoned.
third example
# Contains one parameter. When called, we pass it a name, and it prints a sentence with the name of the person we pass it on. Here we have defined its name function.
def greeting(name):
"" This function print hello message based on the specified name ""
print('Hello '+name+', welcome to our company.')
# greeting() Here we have printed the annotation attached to the function
print(greeting.__doc__)
• We will get the following result when running.
In the following example, we have defined a function whose name is called get_sum. When called, we pass two numbers to it and it returns the product of their sum.
Fourth example
# When called, we pass two numbers to it, and it returns the result of their sum, get_sum. Here we have defined a function named def get_sum(a, b): ""This method returns the sum of the numbers that you passed in a and b""" return a + b; # x in the variable get_sum() here we have stored the product of numbers 3 and 5 that the function will return x = get_sum(3, 5) # which will be equal to 8 x here we have shown the value of the variable print(x)
• We will get the following result when running.
Setting default values for parameters in functions
Python allows you to set default values for the parameters, so when the function is called, you have the option to pass the parameter values in place instead of being forced to.
technical terms
The default value we set for the parameter isDefault Argument.
Technical termsIn the following example, we have defined a function namedprint_language.
This function has only one parameter whose name languagehas text 'English'as the default value.
All this function does when it is called is to print the parameter valuelanguage.
Note: Since the parameter languagehas a value by default, this means that you no longer have to pass a value to it when calling the function because it already has a value.
Example
# And you can not pass a value because it already has a value of language when called. You can pass a value to it in the place of the parameter print_language. Here we have defined a function named
def print_language(language='English'):
print('Your language is:', language)
# 'English' and therefore its value will remain language without passing the value of the parameter print_language() here we have called the function
print_language()
# 'Arabic' so its value will be language for parameter 'Arabic' with print_language() value passed here we called the function
print_language('Arabic')
• We will get the following result when running.
Your language is: Arabic
Define the names of parameters to be given values in Python functions
In most programming languages, when you call a function that contains several parameters, you are forced to pass values for these parameters in the order in which they are placed.
In Python, when you call a function that contains several parameters, you can give values to these parameters without having to be bound by the same order in which they are placed, since inside the function parentheses you can mention the name of the parameter and assign a value to it, and then it does not matter if you follow the given order or not .
In the following example, we have defined a function whose name print_infocontains two parameters nameandsalary.
Then we called it twice:
- The first time, we passed values to the parameters in the order in which they were placed.
- The second time we pass the same values for the parameters, but without being restricted to the order in which they are placed.
Example
# salary and the value of the parameter location name When called, we must pass it the value of the parameter location print_info Here we have defined a function with its name
def print_info(name, salary):
print('Name:', name)
print('Salary:', salary)
print('-----------------')
# In the same order as salary and the number 1500 for the parameter name for parameter 'Nader', passing the text print_info Here we called the function
print_info('Nader', 1500)
# name will be placed in the parameter 'Nader' and the text salary with specifying that the number 1500 will be placed in the parameter print_info here we called the function
print_info(salary=1500, name='Nader')
• We will get the following result when running.
Salary: 1500
------------------
Name: Nader
Salary: 1500
------------------
Building functions that accept an unlimited number of values when calling functions in Python
Sometimes you may need to build a function that handles an indefinite number of values when called. That is, no matter how many values you pass to it, it must process them all.
To build a function that can pass an infinite number of values to it when called, you have to set one parameter for this command.
Simply put *it before the parameter name and the Python interpreter will understand that you can pass an unlimited number of values to that parameter. Then all the values you pass to the function will be grouped inside tuplewhich makes you able to work with them easily.
technical terms
If the number of values that can be passed to the parameter is not specified, these values are saidVariable-length Arguments.
In the following example, we have defined a function whose name print_argsaccepts an indefinite number of values when it is called, then it only displays these values by the loopfor.
All values that will be passed to it will be stored in a single parameter named .*args.
first example
# When called, we can pass an unlimited number of values to it. Then it will print the values we passed to it print_args Here we have defined a function whose name is def print_args(*args): for e in args: print(e) # Passing 10 values of print_args() here we called the function print_args(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
• We will get the following result when running.
2
3
4
5
6
7
8
9
10
In the following example, we have defined a function called that print_averageaccepts an unlimited number of values when called.
The objective of this function is to print the average of the values passed to it, which is equal to the sum of the values passed in divided by their number.
All values that will be passed to it will be stored in a single parameter named .*values.
Note: We relied on the two ready-made functions in Python to get the sum of the values passed and their number sum().len()
second example
# When called, we can pass an unlimited number of values to it. Then it will print the average of the values we passed to it print_average Here we have defined a function whose name is def print_average(*values): print(sum(values)/len(values)) # Passing 4 values of print_total() here we called the function print_average(1, 2, 3, 4)
• We will get the following result when running.
In the following example, we have defined a function whose name print_user_averageis to be printed, the aim of which is to print the name of the person and the average score he obtained.
So, when calling it we must pass it at least two values:
- The first value represents the name of a person which we will store in the name parameteruser.
- The second value or the second set of values represents the marks of this person, which we will store in one parameter of his name*notes.
Note: We relied on the two ready-made functions in Python to get the sum of the values passed and their number sum().len()
third example
# notes and its tags The place of the parameter user When called, we must pass the name of the person in the place of the parameter. print_user_average Here we have defined a function named
# And then you will calculate the person's average (based on his grades) and then display his name and average in an orderly manner
def print_user_average(user, *notes):
avg = sum(notes)/len(notes)
print('The average of', user, 'is:', avg)
# Passing the person's name and 4 values (which represent the person's tags) have print_user_average() here we called the function
print_user_average('Ahmad', 1, 2, 3, 4)
• We will get the following result when running.
Differentiating between variables defined inside and outside functions in Python
When defining new functions, you should pay attention to the names of the variables that you intend to define inside them so that there is no conflict between them and the rest of the variables that are already in the code.
For example, if you define a regular variable, then define a function and put a variable with the same name as the variable outside the function. Then the Python interpreter will ignore the variable that was defined outside the function, so you won't be able to access it from the function, i.e. you won't even be able to display its value.
In the event that you want to inform the Python interpreter that you want to deal with the variable outside the function, whether in order to display or change its value, you will have to put the keyword globalbefore the variable name and on a single line.
technical terms
Variables that are defined inside functions are calledLocal VariablesThis label means that it cannot be accessed directly from outside the function.
Variables that are defined outside functions are called .Global VariablesAnd this label means that it can be accessed from anywhere in the code, even from inside functions.
In the following example, we have declared a variable named x, and then we have defined a function whose name will testonly print its value.
first example
# Its value is 1 x here we have defined a variable named
x = 1
# which is defined outside x prints the value of the variable test here we have defined a function named
def test():
print('Global x =', x)
# which is defined outside x which will print the value of the variable test() here we called the function
test()
• We will get the following result when running.
In the following example, we have declared a variable whose name is x, and then we have defined a function whose name testalso contains a variable whose name xis just printing its value.
Remember: the value declared inside the function will be printed xand not outside the function because the Python interpreter will ignore the external variable.
second example
# Its value is 1 x here we have defined a variable named
x = 1
# which is defined inside x prints the value of the variable test here we have defined a function named
def test():
x = 5
print('Local x =', x)
# which is defined inside x which will print the value of the variable test() here we called the function
test()
# located outside the function. Notice that its value of x has not changed. Here we have printed the value of the variable
print('Global x =', x)
• We will get the following result when running.
Global x = 1
In the following example, we have defined a variable whose name is 1 , and then we have defined a function whose name will only change its value to x.test5 .
Remember: to change the value of a variable from inside a function, but it is essentially outside it, the keyword must be placed globalbefore the variable name and on a single line.
third example
# Its value is 1 x here we have defined a variable named
x = 1
# which is defined outside x changes the value of test here we have defined a function named
def test():
global x
x = 5
# global which we basically defined outside of it and which we accessed by keyword x so you change the value of the variable test() here we called the function
test()
# contained in the outside of the function. Notice that it stayed the same x here we printed a value of
print('Global x =', x)
• We will get the following result when running.
Defining functions in Python style Lambda
If you want to define a function that consists of only one line and returns a value when called, you can define itKAnonymous Function.Then the keyword is used lambdato define it, not the worddef.
The basic form to follow when defining a function with a styleLambdaIn Python it is the following:
• lambda means that you define a new function that does not have a name.
• [arg1 [,arg2,.....argn]] : It means only the parameters that you can set for the function, noting that you must put a comma between each of the two parameters.
• :expression : means the command that will return the value when the function is executed, indicating that the token must be placed :is an imperative.
note
when you defineAnonymous FunctionYou are actually declaring a function that has no name. And since a function can only be called by calling it by its name, the solution is to refer to the function by a variable name. That is, you define a variable and make it equal to the function that you defined, and then the variable name will be considered as the name of the function through which it can be called.
In the following example, we have defined a function .KAnonymous FunctionWhen called, we pass two numbers to it, and it returns the result of subtracting the first number from the second number.
We assign the function to an object named total_payso that we can call it by it.
Example
# total_pay Here we have defined a function that we must pass two values when called in order to return the result of their subtraction and can be called by the object total_pay = lambda price, tax: price - tax # And all it will do is return the result of subtracting the first value from the second value total_pay Here we called the function by the object print(total_pay(500, 40))
• We will get the following result when running.