4.06.2022 15:22 09.
functions_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
9. Functions in Python
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. * As our program grows larger and
larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
There are two types of functions :
Pre-defined functions
User defined functions
In Python a function is defined using the def keyword followed by the function name and parentheses ().
Keyword def that marks the start of the function header.
A function name to uniquely identify the function.
Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of the function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
In [9]:
1 # Take a function sample
2 # Mathematical operations in a function
3
4 def process(x):
5 y1 = x-8
6 y2 = x+8
7 y3 = x*8
8 y4 = x/8
9 y5 = x%8
10 y6 = x//8
11 print(f'If you make the above operations with {x}, the results will be {y1}, {y2}, {y3}, {y4}, {y5}, {y6}.')
12 return y1, y2, y3, y4, y5, y6
13
14 process(5)
If you make the above operations with 5, the results will be -3, 13, 40, 0.625, 5, 0.
Out[9]:
(-3, 13, 40, 0.625, 5, 0)
You can request help using help() function
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [10]:
1 help(process)
Help on function process in module __main__:
process(x)
Call the function again with the number 3.14
In [11]:
1 process(3.14)
If you make the above operations with 3.14, the results will be -4.859999999999999, 11.14, 25.12, 0.39
25, 3.14, 0.0.
Out[11]:
(-4.859999999999999, 11.14, 25.12, 0.3925, 3.14, 0.0)
Functions with multiple parameters
In [2]:
1 # Define a function with multiple elements
2 def mult(x, y):
3 z = 2*x + 5*y + 45
4 return z
5
6 output = mult(3.14, 1.618) # You can yield the output by assigning to a variable
7 print(output)
8 print(mult(3.14, 1.618)) # You can obtain the result directly
9 mult(3.14, 1.618) # This is also another version
59.370000000000005
59.370000000000005
Out[2]:
59.370000000000005
In [20]:
1 # Call again the defined function with different arguments
2 print(mult(25, 34))
265
Variables
The input to a function is called a formal parameter.
A variable that is declared inside a function is called a local variable.
The parameter only exists within the function (i.e. the point where the function starts and stops).
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
A variable that is declared outside a function definition is a global variable, and its value is accessible and
modifiable throughout the program.
In [5]:
1 # Define a function
2 def function(x):
3
4 # Take a local variable
5 y = 3.14
6 z = 3*x + 1.618*y
7 print(f'If you make the above operations with {x}, the results will be {z}.')
8 return z
9
10 with_golden_ratio = function(1.618)
11 print(with_golden_ratio)
If you make the above operations with 1.618, the results will be 9.934520000000001.
9.934520000000001
In [8]:
1 # It starts the gloabal variable
2 a = 3.14
3
4 # call function and return function
5 y = function(a)
6 print(y)
If you make the above operations with 3.14, the results will be 14.500520000000002.
14.500520000000002
In [9]:
1 # Enter a number directly as a parameter
2 function(2.718)
If you make the above operations with 2.718, the results will be 13.23452.
Out[9]:
13.23452
Without return statement, the function returns None
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [10]:
1 # Define a function with and without return statement
2 def msg1():
3 print('Hello, Python!')
4
5 def msg2():
6 print('Hello, World!')
7 return None
8
9 msg1()
10 msg2()
Hello, Python!
Hello, World!
In [15]:
1 # Printing the function after a call indicates a None is the default return statement.
2 # See the following prontings what functions returns are.
3
4 print(msg1())
5 print(msg2())
Hello, Python!
None
Hello, World!
None
Concatetantion of two strings
In [18]:
1 # Define a function
2 def strings(x, y):
3 return x + y
4
5 # Testing the function 'strings(x, y)'
6 strings('Hello', ' ' 'Python')
Out[18]:
'Hello Python'
Simplicity of functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [26]:
1 # The following codes are not used again.
2 x = 2.718
3 y = 0.577
4 equation = x*y + x+y - 37
5 if equation>0:
6 equation = 6
7 else: equation = 37
8
9 equation
Out[26]:
37
In [27]:
1 # The following codes are not used again.
2 x=0
3 y=0
4 equation = x*y + x+y - 37
5 if equation<0:
6 equation = 0
7 else: equation = 37
8
9 equation
Out[27]:
In [28]:
1 # The following codes can be write as a function.
2 def function(x, y):
3 equation = x*y + x+y - 37
4 if equation>0:
5 equation = 6
6 else: equation = 37
7 return equation
8
9 x = 2.718
10 y = 0.577
11 function(x, y)
Out[28]:
37
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [29]:
1 # The following codes can be write as a function.
2 def function(x, y):
3 equation = x*y + x+y - 37
4 if equation<0:
5 equation = 6
6 else: equation = 37
7 return equation
8
9 x=0
10 y=0
11 function(x, y)
Out[29]:
Predefined functions like print(), sum(), len(), min(), max(), input()
In [31]:
1 # print() is a built-in function
2 special_numbers = [0.577, 2.718, 3.14, 1.618, 1729, 6, 28, 37]
3 print(special_numbers)
[0.577, 2.718, 3.14, 1.618, 1729, 6, 28, 37]
In [32]:
1 # The function sum() add all elements in a list or a tuple
2 sum(special_numbers)
Out[32]:
1808.053
In [33]:
1 # The function len() gives us the length of the list or tuple
2 len(special_numbers)
Out[33]:
Using conditions and loops in functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [44]:
1 # Define a function including conditions if/else
2
3 def fermentation(microorganism, substrate, product, activity):
4 print(microorganism, substrate, product, activity)
5 if activity < 1000:
6 return f'The fermentation process was unsuccessful with the {product} activity of {activity} U/mL from {substrate}
7 else:
8 return f'The fermentation process was successful with the {product} activity of {activity} U/mL from {substrate} us
9
10 result1 = fermentation('Aspergillus niger', 'molasses', 'inulinase', 1800)
11 print(result1)
12 print()
13 result2 = fermentation('Aspergillus niger', 'molasses', 'inulinase', 785)
14 print(result2)
15
Aspergillus niger molasses inulinase 1800
The fermentation process was successful with the inulinase activity of 1800 U/mL from molasses using A
spergillus niger.
Aspergillus niger molasses inulinase 785
The fermentation process was unsuccessful with the inulinase activity of 785 U/mL from molasses using
Aspergillus niger. You should repeat the fermentation process.
In [50]:
1 # Define a function using the loop 'for'
2
3 def fermentation(content):
4 for parameters in content:
5 print(parameters)
6
7 content = ['Stirred-tank bioreactor' ,'30°C temperature', '200 rpm agitation speed', '1 vvm aeration', '1% (v/v) inoculum
8 fermentation(content)
Stirred-tank bioreactor
30°C temperature
200 rpm agitation speed
1 vvm aeration
1% (v/v) inoculum ratio
pH control at 5.0
Adjustiing default values of independent variables in functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [53]:
1 # Define a function adjusting the default value of the variable
2
3 def rating_value(rating = 5.5):
4 if rating < 8:
5 return f'You should not watch this film with the rating value of {rating}'
6 else:
7 return f'You should watch this film with the rating value of {rating}'
8
9 print(rating_value())
10 print(rating_value(8.6))
You should not watch this film with the rating value of 5.5
You should watch this film with the rating value of 8.6
Global variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.
In [56]:
1 # Define a function for a global variable
2 language = 'Python'
3
4 def lang(language):
5 global_var = language
6 print(f'{language} is a program language.')
7
8 lang(language)
9 lang(global_var)
10
11 """
12 The output gives a NameError, since all variables in the function are local variables,
13 so variable assignment is not persistent outside the function.
14 """
Python is a program language.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/4270999454.py in <module>
8 lang(language)
----> 9 lang(global_var)
NameError: name 'global_var' is not defined
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [58]:
1 # Define a function for a global variable
2 language = 'JavaScript'
3
4 def lang(language):
5 global global_var
6 global_var = 'Python'
7 print(f'{language} is a programing language.')
8
9 lang(language)
10 lang(global_var)
JavaScript is a programing language.
Python is a programing language.
Variables in functions
The scope of a variable is the part of the program to which that variable is accessible.
Variables declared outside of all function definitions can be accessed from anywhere in the program.
Consequently, such variables are said to have global scope and are known as global variables.
In [76]:
1 process = 'Continuous fermentation'
2
3 def fermentation(process_name):
4 if process_name == process:
5 return '0.5 g/L/h.'
6 else:
7 return '0.25 g/L/h.'
8
9 print('The productiovity in continuous fermentation is', fermentation('Continuous fermentation'))
10 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
11 print('Continuous fermentation has many advantages over batch fermentation.')
12 print(f'My favourite process is {process}.')
The productiovity in continuous fermentation is 0.5 g/L/h.
The productiovity in batch fermentation is 0.25 g/L/h.
Continuous fermentation has many advantages over batch fermentation.
My favourite process is Continuous fermentation.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [77]:
1 # If the variable 'process' is deleted, it returns a NameError as follows
2 del process
3
4 # Since the variable 'process' is deleted, the following function is an example of local variable
5 def fermentation(process_name):
6 process = 'Continuous fermentation'
7 if process_name == process:
8 return '0.5 g/L/h.'
9 else:
10 return '0.25 g/L/h.'
11
12 print('The productiovity in continuous fermentation is', fermentation('Continuous fermentation'))
13 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
14 print('Continuous fermentation has many advantages over batch fermentation.')
15 print(f'My favourite process is {process}.')
The productiovity in continuous fermentation is 0.5 g/L/h.
The productiovity in batch fermentation is 0.25 g/L/h.
Continuous fermentation has many advantages over batch fermentation.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/2006816728.py in <module>
13 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
14 print('Continuous fermentation has many advantages over batch fermentation.')
---> 15 print(f'My favourite process is {process}.')
NameError: name 'process' is not defined
In [81]:
1 # When the global variable and local variable have the same name:
2
3 process = 'Continuous fermentation'
4
5 def fermentation(process_name):
6 process = 'Batch fermentation'
7 if process_name == process:
8 return '0.5 g/L/h.'
9 else:
10 return '0.25 g/L/h.'
11
12 print('The productiovity in continuous fermentation is', fermentation('Continuous fermentation'))
13 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
14 print(f'My favourite process is {process}.')
The productiovity in continuous fermentation is 0.25 g/L/h.
The productiovity in batch fermentation is 0.5 g/L/h.
My favourite process is Continuous fermentation.
(args) and/or (*args) and Functions
When the number of arguments are unkknown for a function, then the arguments can be packet into a tuple or
a dictionary
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [84]:
1 # Define a function regarding a tuple example
2 def function(*args):
3 print('Number of elements is', len(args))
4 for element in args:
5 print(element)
6
7 function('Aspergillus niger', 'inulinase', 'batch', '1800 U/mL activity')
8 print()
9 function('Saccharomyces cerevisia', 'ethanol', 'continuous', '45% yield', 'carob')
10
Number of elements is 4
Aspergillus niger
inulinase
batch
1800 U/mL activity
Number of elements is 5
Saccharomyces cerevisia
ethanol
continuous
45% yield
carob
In [98]:
1 # Another example regarding 'args'
2 def total(*args):
3 total = 0
4 for i in args:
5 total += i
6 return total
7
8 print('The total of the numbers is', total(0.577, 2.718, 3.14, 1.618, 1729, 6, 37))
The total of the numbers is 1780.053
In [88]:
1 # Define a function regarding a dictionary example
2 def function(**args):
3 for key in args:
4 print(key, ':', args[key])
5
6 function(Micoorganism='Aspergillus niger', Substrate='Molasses', Product='Inulinase', Fermentation_mode='Batch', A
Micoorganism : Aspergillus niger
Substrate : Molasses
Product : Inulinase
Fermentation_mode : Batch
Activity : 1800 U/mL
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 11/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [96]:
1 # Define a function regarding the addition of elements into a list
2 def addition(nlist):
3 nlist.append(3.14)
4 nlist.append(1.618)
5 nlist.append(1729)
6 nlist.append(6)
7 nlist.append(37)
8
9 my_list= [0.577, 2.718]
10 addition(my_list)
11 print(my_list)
12 print(sum(my_list))
13 print(min(my_list))
14 print(max(my_list))
15 print(len(my_list))
[0.577, 2.718, 3.14, 1.618, 1729, 6, 37]
1780.053
0.577
1729
Doctsting in Functions
In [97]:
1 # Define a function
2 def addition(x, y):
3 """The following function returns the sum of two parameters."""
4 z = x+y
5 return z
6
7 print(addition.__doc__)
8 print(addition(3.14, 2.718))
The following function returns the sum of two parameters.
5.8580000000000005
Recursive functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 12/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [103]:
1 # Calculating the factorial of a certain number.
2
3 def factorial(number):
4 if number == 0:
5 return 1
6 else:
7 return number*factorial(number-1)
8
9 print('The value is', factorial(6))
The value is 720
In [107]:
1 # Define a function that gives the total of the first ten numbers
2 def total_numbers(number, sum):
3 if number == 11:
4 return sum
5 else:
6 return total_numbers(number+1, sum+number)
7
8 print('The total of first ten numbers is', total_numbers(1, 0))
The total of first ten numbers is 55
Nested functions
In [111]:
1 # Define a function that add a number to another number
2 def added_num(num1):
3 def incremented_num(num1):
4 num1 = num1 + 1
5 return num1
6 num2 = incremented_num(num1)
7 print(num1, '------->>', num2)
8
9 added_num(25)
25 ------->> 26
nonlocal function
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 13/14
4.06.2022 15:22 09. functions_python - Jupyter Notebook
In [112]:
1 # Define a function regarding 'nonlocal' function
2 def print_year():
3 year = 1990
4 def print_current_year():
5 nonlocal year
6 year += 32
7 print('Current year is', year)
8 print_current_year()
9 print_year()
Current year is 2022
In [117]:
1 # Define a function giving a message
2 def function(name):
3 msg = 'Hi ' + name
4 return msg
5
6 name = input('Enter a name: ')
7 print(function(name))
Hi Mustafa
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 14/14