6. Function
▸ Function is a named block of code that is design to do a specific job.
▸ The basic idea is write the code once and use it again and again. The first
step to code reuse.
▸ You can call the function whenever you like in your code.
1. def function_name(paramter_1,parameter_2,…):
2. someCode
3. someCode
4. someCode
5. return someValue
“function name” is an identifier so it must follow identifier naming rules!
Positional
Parameters - The
order matters
8. Example of Defining and Calling a Function
▸ Function without parameters
▸ Function with parameters
▸ Calling a function with or without arguments
1. def welcome_passenger():
2. print(“Dear Passenger welcome onboard ”)
1. def welcome_passenger(passengerName):
2. print(“Dear Mr/Ms” + passengerName + “ Welcome Onboard”)
1. welcome_passenger()
2. welcome_passenger(“Tehrani”)
parameter
argument
10. P A R A M E T E R V S .
ARGUMENT
Two names for the same things. Parameters are inside
the function and Arguments are outside the function
11. Parameters Default Values
▸ We can define a default value for each parameter. If an argument for
for a parameters is provided in the function call python use the
argument value and if not its uses the parameter’s default value
1. def welcome_message(name, country =“Japan”):
2. print(“Mr./Ms. ” + name + “ from ”+country + “ Welcome To Iran” )
1. welcome_message(name=“John”, country=”Germany”)
2. welcome_message(name=“John”,)
Be careful about Arguments Error
“Japan” is the
default value
12. Return a Value
▸ Function can process some data and then return a value or set of
values
▸ Calling the function with return value
1. def format_name(first_name, last_name):
2. full_name = first_name.title() + “ “ + last_name.title()
3. return full_name
1. print(format_name(“ehsan”,”kaviani”))
2. formated_name = formated_name(“ehsan”,”Kaviani”)
13. Return Multiple Value
▸ A Function can return any object including data structures like
dictionary or list.
1. def add_key_value(dic,key,value):
2. dic[key] = value
3. return dic
5. student_dic_0 = {“name” : ”Kaveh” , “family”:”Sarkhosh”}
6. student_dic_0 = add_key_value(student_dic_0, ‘age’, 20)
7. print(student_dic_0)
It is a Dictionary
data structure
14. WHEN YOU PASS A LIST OR
DICTIONARY ANY CHANGE TO
THE OBJECT IS PERMANENT!
So be careful when you are working with list or dictionary
15. Keyword Arguments
▸ Is a name-value pair that you pass to a function
▸ Calling the function
1. def welcome_message(name, country ):
2. print(“Mr./Ms. ” + name + “ from ”+country + “ Welcome To Iran” )
1. welcome_message(name=“John”, country=”Germany”)
2. welcome_message(country=”Iran”, name=“Babak”)
You have to use the exact names of the parameters!!!! Exact
16. Pass Variable Number of Arguments
▸ *args and **kwargs are used as parameters in function definitions and
allows to pass a variable number of arguments to the calling function.
▸ *args allows you to pass a non-keyworded, variable length tuple
argument list to the
▸ **kwargs allows you to pass keyworded, variable length dictionary
argument list to the calling function
17. Example of Function With Variable Number of Parameters
▸ It should be noted that the single asterisk (*) and double asterisk (**) are
the important elements here and the words args and kwargs are used
only by convention.
1. def sample_function(name,*args,**kwargs):
2. print(f”Hello {name} here is the list of item you sent:”)
3. for item in args :
4. print(item)
5. print(f”Also here is the list of key-value you have sent:”)
6. for kw in kwargs :
7. print(kw,” : ”,kwargs[kw])
18. BY USING FUNCTION
YOU CAN SEPARATE
BLOCK OF CODE FROM
YOUR MAIN CODE
The code is much more readable and manageable
19. Using Modules
▸ You can store your functions in separate file called module and then
import the module in your main program.
▸ Module is a file with .py extension.
▸ You can put all functions in a module.
1. def add_key_value(dic,key,value):
2. dic[key] = value
3. return dic
my_module.py
20. Importing an Entire Module - All its Functions
▸ You can use a module by importing it wherever you need the module
function!
▸ Put the import at the top of your main code.
▸ The general rule is you have to define a function before you use it.
1. import my_module
2. #or
3. from my_module import *
main.py
There is a small difference between these two!!! What is it?
26. Importing Specific Function
▸ There is some big module with lots of function. But we just want to use
some specific functions so we can partially import the module.
1. from my_module import function_1, function_2
2. …
main.py
27. Aliasing Module Name or Function Name
▸ We can use alias to make module name shorter
1. import tensorflow as tf
2. from tensorflow.core import debug as tfd
main.py
28. THERE ARE MANY
MODULES THAT YOU CAN
USE IN YOUR PROGRAM
Using pip directly or using pip in pyCharm
29. Python Standard Libraries and Modules
▸ Built-in modules are part of python standard library
▸ python library reference manual
1. import math
2. import pathlib
3. import os
4. import json
5. import csv
6. …
https://docs.python.org/3/library/
34. Python Third-Party Libraries and Modules - Package
▸ Third-party modules or libraries can be installed and managed using
Python’s package manager pip.
▸ You can use Operating System Command line
▸ You can use PyCharm Command Line
▸ You can use PyCharm Package Management Tool
pip install module_name