Function. Concept of function. General form. Examples of declaring and using functions
- 1. What is a function? Function definition. The advantages of using functions
- 2. Instruction def. The general form for declaring a function in Python. Creating a function
- 3. Function call
- 4. An example of declaring and using a function without parameters
- 5. An example of declaring and using a function that receives 1 parameter
- 6. An example of declaring and using a function that receives a parameter and returns the result
- 7. An example of a function declaration in an if statement. Alternative implementation
- 8. Polymorphism in functions. Examples
- 9. Using local variables inside functions. Example
Search other websites:
1. What is a function? Function definition. The advantages of using functions
A function is a means (method) of grouping fragments of program code in such a way that this program code can be called multiple times by using the name of the function.
Using functions in Python programs provides the following related benefits:
- avoiding the repetition of identical fragments of code in different parts of the program;
- reducing the redundancy of the source code of the program. As a result, reducing logical programming errors;
- improved perception of the program source code in cases where instead of blocks of numerous instructions (operators), the names of ready-tested functions are called. This, in turn, also reduces errors;
- simplification of changes in repeatable code blocks organized as functions. It is enough to make changes only in the body of the function, then in all calls to this function these changes will be taken into account;
- using functions, it’s convenient to break up a complex system into simpler parts. So functions are a convenient way to structure a program;
- reduction of programming labor costs, and, therefore, increase in programmer productivity.
The following features are common to functions in the Python programming language:
- functions can return a result;
- functions can receive input parameters that affect the result.
2. Instruction def. The general form for declaring a function in Python. Creating a function
For a function to be used in a program, it needs to be created (declared). In Python, creating (or declaring) a function is done using the def statement. If the interpreter reaches the def statement, it creates a new function object and associates the packed function code with its name.
A function may or may not return a value. If the function does not return a value, then it is considered that it automatically returns a None object, which is ignored. In this case, the return statement is optional. The general form of such a function is as follows:
def <name>(arg1, arg2, ..., argN): <statement1> <statement2> ... <statementN>
- name – the name of the function with which the function object will be associated and a list of parameters (arg1, arg2, …, argN). The function object gets the name name and is created at runtime (in Python there is no compilation time);
- arg1, arg2, argN – list of parameters that the function can receive. The function can also be without parameters;
- statement1, statement2, statementN – one or more instructions that follow with digressions regarding def.
If the function returns a value, then its general form is as follows
def <name>(arg1, arg2, ..., argN): <statement1> <statement2> ... <statementN> return <value>
- name – the name of function;
- arg1, arg2, …, argN – functions parameters (if there are any);
- statement1, statement2, statementN – instructions that are implemented in the body of the function;
- value – the value returned by the function.
Defining a function using the def statement can be implemented inside other statements, for example, inside an if statement.
3. Function call
After the function is created (declared), you can call it. A function is called using its name and a list of parameters.
For example. Let the following function be declared
def Mult2(a, b): return a*b
then her call may be, for example, such
res = Mult2(7,9)
As a result, res = 63.
The interpreter, having met the def statement, performs the following actions:
- creates a new function object named Mult2;
- packs the program code of the function and binds the object with the name Mult2;
- calls a function in the program.
If you specify
res = Mult2('abc',3)
then res = ‘abcabcabc’.
4. An example of declaring and using a function without parameters
The following is an example of declaring and using a function that does not contain parameters. The function is called Hello and displays the text “Hello world!” 3 times.
# Functions without parameters. # Declare a function called Hello(), # which displays "Hello world!" to the screen. def Hello(): print("Hello world!") # Call the Hello() function in a while loop i=0 while i<3: Hello() i=i+1
5. An example of declaring and using a function that receives 1 parameter
The following is an example of creating and using the Print3() function, which receives one parameter and displays it 3 times.
# Declare a function named Print5(), # which displays the value of the parameter t on the screen 3 times def Print3(t): i=0 while i<3: print(t) i=i+1 # Call Print3() function for different types of parameters Print3('abc') Print3(2.85) Print3(-88) Print3(True)
The result of the program
abc abc abc 2.85 2.85 2.85 -88 -88 -88 True True True
As you can see from the result, in Python, the type of parameter that is passed to the function can be any. The interpreter recognizes it by the object that is passed as a parameter.
6. An example of declaring and using a function that receives a parameter and returns the result
The following is an example of a function that receives a parameter and returns a result. The function reverses the string.
# Function reversing string def Reverse(s): s2 = '' i = len(s)-1 while i>=0: s2 = s2 + s[i] i = i-1 return s2 # Invoke function Reverse() s1 = "abcdef" s2 = Reverse(s1) # s2 = 'fedcba' print("s2 = ", s2)
The result of the program
s2 = fedcba
7. An example of a function declaration in an if statement. Alternative implementation
Defining a function using the def tool can be nested in another statement, for example, an if statement. In this case, an alternative arises when executing the program.
Example. In the example, based on the entered value of n, a function Fn() is created, which calculates a trigonometric expression according to the following rule:
- sin(x)*cos(x), if n==1;
- sin(x2)+cos(x), if n==2;
- 1-sin(x), otherwise.
Then this function is called for the given value of x.
# Given a value of n, determine the function Fn (), # that calculates: # sin(x)*cos(x), if n==1 # sin(x*x)+cos(x), if n==2 # 1-sin(x), otherwise # Import Math Library import math # Input the value of n n = int(input('n = ')) x = float(input('x = ')) # Determine the function code Fn() if (n==1): def Fn(x): print("n==1. res = sin(x)*cos(x).") return math.sin(x)*math.cos(x) else: if (n==2): def Fn(x): print("n==2. res = sin(x*x)+cos(x)") return math.sin(x*x)+math.cos(x) else: def Fn(x): print("n==3. res = 1-sin(x)") return 1-math.sin(x) # Call function Fn() res = Fn(x) print("res = ", res)
The result of the program
n = 3 x = 1.2 n==3. res = 1-sin(x) res = 0.06796091403277371
8. Polymorphism in functions. Examples
In Python, all data is represented by objects. Objects define the syntactic content of an operation. Operation support for different types of objects is provided due to polymorphism. Polymorphism is the dependence of the content of an operation on the type of objects to which it is applied. Polymorphism in a function manifests itself when parameters are passed to the function. Function parameters are objects that can be of different types.
Function parameters are used in operations that can handle different types. In Python, this process is called dynamic typing.
For example, the operation * can be applied to both numbers and strings. In the case of numbers, this operation means multiplication. In the case of strings, this operation allows you to repeat a string a specified number of times.
Example 1. The Mult() function, which takes two parameters a, b is demonstrated. For the obtained parameters, operation * is performed.
# Polymorphism in functions # Function Mult() def Mult(a,b): return a*b # Call Mult() function for different types of objects # 1. For numbers x = 8 y = 5 z = Mult(x,y) # z = 40 # 2. For strings s1 = "Hello " n = 3 s2 = Mult(s1,n) # s2 = 'Hello Hello Hello'
Example 2. The Summ() function is demonstrated, which takes two parameters a, b. The function returns the result of the + operation on the parameters.
# Polymorphism in functions # Function Summ() def Summ(a,b): return a+b # Call Summ() function for different types of objects # 1. For numbers x = 18 y = 3 z = Summ(x,y) # z = 40 # 2. For strings s1 = "Hello " s2 = "world!" s3 = Summ(s1,s2) # s3 = 'Hello world!'
9. Using local variables inside functions. Example
Inside a function, local variables can be declared. A local variable is a name (object) that is available only inside a function definition (def statement). A local variable exists only at runtime.
In the body of any function, local variables are determined based on the following features:
- if the variable is located on the left side of the assignment operation;
- if the variable (name) is the parameter (argument) of the function;
- if the variable is an iterator in a for loop.
Example. In the example, the SquareTriangle() function is created, which calculates the area of the triangle by its sides. The lengths of the sides of the triangle with the names a, b, c are the input parameters of the function. If it is impossible to form a triangle with a, b, c, then the function returns None.
Then the SquareTriangle() function is called and the result of the return from the function is processed.
# Calculate the area of a triangle by the lengths of its sides a, b, c # Import Math Library import math def SquareTriangle(a,b,c): if (((a+b)<c) or ((b+c)<a) or ((a+c)<b)): return None else: p = (a+b+c)/2 # this is a local variable p s = math.sqrt(p*(p-a)*(p-b)*(p-c)) # local variable s return s # Using function SquareTriangle() s = SquareTriangle(5,4,5) if (s==None): print("The values of a, b, c is incorrect.") else: print("s = ", s)
The SquareTriangle() function creates two local variables with the names p, s.
The result of the program
s = 9.16515138991168