SlideShare a Scribd company logo
1 of 42
Download to read offline
CS.QIAU - Winter 2020
PYTHONFunctions and Modules - Session 3
Omid AmirGhiasvand
Programming
also called Procedural
PROGRAMMING
IS A TYPE OF IMPERATIVE
PROGRAMMING PARADIGM
STRUCTURED
PROGRAMMING IS A
PROGRAMMING PARADIGM THAT USES
STATEMENTS THAT CHANGE A
PROGRAM’S STATE.
IMPERATIVE
PROGRAMMING IS
APROGRAMMING PARADIGM THAT
EXPRESSES THE LOGIC OF A
COMPUTATION WITHOUT DESCRIBING ITS
CONTROL FLOW.
DECLARATIVE
IMPERATIVE VS.
DECLARATIVEHuge paradigm shift. Are you ready?
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
FUNCTIONS MUST BE
BEFORE BEING CALLED.
DEFINED
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
we can use
pass as a place
holder
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
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
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”)
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
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
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
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
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])
BY USING FUNCTION
YOU CAN SEPARATE
BLOCK OF CODE FROM
YOUR MAIN CODE
The code is much more readable and manageable
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
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?
my_functions.py
in the root of the
project
we can add
function here
Unsolved reference
import
my_function
module
we have
to write imported
module name
did you get
what just
happened?
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
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
THERE ARE MANY
MODULES THAT YOU CAN
USE IN YOUR PROGRAM
Using pip directly or using pip in pyCharm
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/
very clean main
function
list of files and directory
in data directory
importing Path
p reference current
directory
list of files and directory
in project root
Change
current path
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
terminal
command
Preference
menu
Package
installed in project
venv
Python Interpreter
setting
To Install new
Package
numpy and
pandas are installed
LAST THING ABOUT FUNCTION
IN PYTHON FUNCTION
IS AN OBJECTcan be assigned to a variable
try to understand
what just happened
“The Unexamined Life Is Not Worth Living”

More Related Content

What's hot (20)

Function C++
Function C++ Function C++
Function C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Built in function
Built in functionBuilt in function
Built in function
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in python
Functions in python Functions in python
Functions in python
 
Python modules
Python modulesPython modules
Python modules
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Functions
FunctionsFunctions
Functions
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
 
user defined function
user defined functionuser defined function
user defined function
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming
 
Python recursion
Python recursionPython recursion
Python recursion
 

Similar to Python Programming - Functions and Modules

Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfDaddy84
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfSudhanshiBakre1
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsRuth Marvin
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 

Similar to Python Programming - Functions and Modules (20)

Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
 
function.pptx
function.pptxfunction.pptx
function.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
4. function
4. function4. function
4. function
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Advance python
Advance pythonAdvance python
Advance python
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
FUNCTIONS.pptx
FUNCTIONS.pptxFUNCTIONS.pptx
FUNCTIONS.pptx
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 

Recently uploaded

WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 

Recently uploaded (20)

WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 

Python Programming - Functions and Modules

  • 1. CS.QIAU - Winter 2020 PYTHONFunctions and Modules - Session 3 Omid AmirGhiasvand Programming
  • 2. also called Procedural PROGRAMMING IS A TYPE OF IMPERATIVE PROGRAMMING PARADIGM STRUCTURED
  • 3. PROGRAMMING IS A PROGRAMMING PARADIGM THAT USES STATEMENTS THAT CHANGE A PROGRAM’S STATE. IMPERATIVE
  • 4. PROGRAMMING IS APROGRAMMING PARADIGM THAT EXPRESSES THE LOGIC OF A COMPUTATION WITHOUT DESCRIBING ITS CONTROL FLOW. DECLARATIVE
  • 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
  • 7. FUNCTIONS MUST BE BEFORE BEING CALLED. DEFINED
  • 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
  • 9. we can use pass as a place holder
  • 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?
  • 21. my_functions.py in the root of the project we can add function here
  • 22.
  • 25. did you get what just happened?
  • 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/
  • 30. very clean main function list of files and directory in data directory
  • 31. importing Path p reference current directory
  • 32. list of files and directory in project root
  • 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
  • 36. Preference menu Package installed in project venv Python Interpreter setting To Install new Package
  • 37.
  • 38. numpy and pandas are installed
  • 39. LAST THING ABOUT FUNCTION
  • 40. IN PYTHON FUNCTION IS AN OBJECTcan be assigned to a variable
  • 41. try to understand what just happened
  • 42. “The Unexamined Life Is Not Worth Living”