Python Functions
What are the functions?
Functions allow us to group code commands under one name for reuse.
Python contains several predefined functions, for example, max (returns the largest value) and min (returns the smallest value), since each function has a specific role that is performed by following the commands contained within it.
Why might we use functions?
We may find ourselves writing a program needing to rewrite a set of commands more than once in different locations. And re-copying and pasting the commands as a whole makes the final code difficult to read because it is full and gives it a somewhat flaky appearance.
To avoid this duplication, we simply create a function that combines these commands, and when we call them by typing the name of the function, those commands are simply executed. Functions are a very basic concept in programming languages for their important role.
How to create a function?
To create a function, we follow the following approach:
def function_name (Parameter1, ...):
p = 1 # We write the commands here
def is short for define. That is, it is the keyword that allows defining/creating a function. Next to it, we write the function name, which must respect the same conditions as writing the variable names.
Between the parentheses, parameters or parameters are simply written that are used in the internal commands of the function. The function may not contain any parameter and it may contain several parameters.
Then, below the name, we write the commands that our function will contain.
Take, for example, the second application in the previous tutorial:
a = input ('Please enter a random number:')
a = int (a)
for i in range (0,10):
a + = 1
print (a)
Now let's write a function that contains these commands and once called the code will be executed:
def calc ():
a = 0
for i in range (0,10):
a + = 1
print (a)
calc ()
Notes:
When we write a function, it is only executed when we call or ask it by typing the function name and its parameters if they exist. In the above example, the function is executed according to our request in line 7, by typing calc () you should also pay attention. To parentheses, they are necessary in functions and must always be written even if the function does not contain parameters. The function at the top will always show the same result because the variable is constant in this case and always equals 0
What if we want to change the value of a?
The code can be written as follows:
def calc (a):
for i in range (0,10):
a + = 1
print (a)
calc (2)
Notes:
The variable is enclosed in the parentheses of the calc function, which now makes it a parameter for the function.
When we ask the function, we must write a number between the parentheses, otherwise, this error will appear:
This message makes it clear that there is a missing element which is 'a'. So the parameter must be written in the parentheses.
What if the user does not enter a parameter between the function brackets?
A default parameter can be written and used if the user has not entered a value.
And that is as follows:
def calc (a = 3):
for i in range (0,10):
a + = 1
print (a)
calc ()
Where we write the parameter or variable and insert the value 3 into it using the symbol =.
When executing this code, the following result appears:
If we clearly notice that the code executed without problems and that the value that was used is the default value 3.
If a different value is entered into the function parameter:
def calc (a = 3):
for i in range (0,10):
a + = 1
print (a)
calc (5)
Upon implementation, the following result appears:
The count starts from 6, so the value used is the 5 that we entered previously!
Add another parameter:
Let's take the application of the multiplication table that we saw earlier. If we want to define the number by which we will multiply a number instead of the number 10 only, we can use the following method:
def table (number, p = 11):
for i in range (1, p):
print (number, 'x', i, '=', number * i)
When entering the number that we want to calculate a multiplication table, for example, 5, the result will appear as follows:
When we enter both the number and the number of numbers we want to multiply by, we simply write both parameters:
In the following writing, the same order of transactions should be respected:
In the following writing, the ranking does not affect transactions:
This is because we rewrite the parameter and insert the value into it using the symbol =, so the order here does not affect it.
What if we wrote the parameter with the default value before the normal parameter in the function?
When writing the code in the following way, i.e. the default parameter p = 11 is written before the normal parameter number:
def table (p = 11, number):
for i in range (1, p):
print (number, 'x', i, '=', number * i)
table (5)
The following message will appear:
And as we can see in the message, it alerts us that we have written a normal parameter after a default parameter.
So when writing the default parameters in the functions, you should pay attention to this command and write the default operators after the normal operators in case both types are present.
Note: that in the above example we are using the for loop and the range function, as the second number in the range function is not included in the loop, so one number must always be added to the number.
This can be avoided by using the while loop in the following way:
def table (number, p = 10):
i = 0
while i <= p:
print (number, 'x', i, '=', number * I)
i + = 1
table (5)
What is the difference between Parameter and Argument in Functions?
A parameter is a variable related to the defined function. For example, in the above example, we have a variable number, which is a parameter for the table function.
The argument is the value held by the parameter. For example, in the example above, the variable number has the value 5 (when we asked the function, we entered the value 5 as follows: table (5)).
Point of similarity between the functions and the Variables:
When we define a function, and we define another function under the same name as the first function, the compiler deletes the content of the first function and preserves the content of the second function, since they have the same name and writing another function under the same name requires deleting the previous one.
This applies to variables as well:
Return command
To understand this command or statement, we must compare it with the print command.
The print command returns a result to the user that shows what the function does. So that this command does not save that result in a specifically designated space (such as variables, for example).
But the return command saves this result for later use, and this is what distinguishes this command.
Functions always return a specific result, however it is. In case we don't use the return or yield command (we'll talk about it later), then the result that the function returns is None, meaning nothing.
In the following simple example, the matter becomes more clear:
def square_root (a):
return (a * a)
def result (a):
print ('The square root of', a, 'is', square_root (a))
result (2)
We created two functions: the first calculates the square root of the number a, and the second displays a message to the user that includes the variable a and the result that appeared in the previous function of the square root.
When using the return command in place of print, the result appears as follows when calling the result (2):
Note that the function was working correctly and result 4 appeared as it should if the return command saves the result 4 for further use.
But when we write print instead of return, the result will be different:
def square_root (a):
print (a * a)
def result (a):
print ('The square root of', a, 'is', square_root (a))
result (2)
The number 4 was printed, which is the square root of 2, and then the message was shown, but instead of writing the result 4, None was written, and as we said earlier, using print does not save the result and returns None when using the function from other function methods.
Therefore, it is preferable to use the return command, especially when we need to use the function within other functions or in other operations.
Lambda functions:
The lambda functions are shorter and shorter than the functions defined by the def keyword.
The word lambda allows us to create functions as well, in a short and quick way.
Example:
Let's write a function that computes the square of a number:
lambda x: x * x
When we press Enter in the translator, the following message appears:
If we want to call it, we must store the function in a variable, as opposed to functions defined by def.
a = lambda x: x * x
And in order to calculate the square of the count 5, for example, we write the number 5 in the parentheses of the variable a that contains the function:
If we want to use more than one parameter, for example, we want to calculate the multiplication of two numbers, we would write the function as follows:
So, we conclude that the lambda function is written in the following way:
variable = lambda parameter1, parameter2, parameter3 ...: instructions
What is the benefit of the lambda functions and when do we use them?
The lambda functions are anonymous because they are not necessarily associated with a name. It can also include only one expression. They are short and concise. And it may be better to use them than to use the functions defined by def in certain cases.