SlideShare a Scribd company logo
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
Python Programming - Functions and Modules
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
Python Programming - Functions and Modules
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++
Shahzad Afridi
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Built in function
Built in functionBuilt in function
Built in function
MD. Rayhanul Islam Sayket
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
Swapnil Yadav
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
Functions in python
Functions in python Functions in python
Functions in python
baabtra.com - No. 1 supplier of quality freshers
 
Python modules
Python modulesPython modules
Python modules
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Shakti Singh Rathore
 
Function overloading
Function overloadingFunction overloading
Function overloading
Sudeshna Biswas
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Functions
FunctionsFunctions
Functions
zeeshan841
 
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
Srajan Mor
 
user defined function
user defined functionuser defined function
user defined function
King Kavin Patel
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming
GaurangVishnoi
 
Python recursion
Python recursionPython recursion
Python recursion
Prof. Dr. K. Adisesha
 
4. python functions
4. python   functions4. python   functions
4. python functions
in4400
 

Similar to Python Programming - Functions and Modules (20)

Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
AkhilTyagi42
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions in Python with all type of arguments
Functions in Python with all type of argumentsFunctions in Python with all type of arguments
Functions in Python with all type of arguments
riazahamed37
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Python functions
Python functionsPython functions
Python functions
ToniyaP1
 
Python functions PYTHON FUNCTIONS1234567
Python functions PYTHON FUNCTIONS1234567Python functions PYTHON FUNCTIONS1234567
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
beginners_python_cheat_sheet_pcc_functions.pdf
beginners_python_cheat_sheet_pcc_functions.pdfbeginners_python_cheat_sheet_pcc_functions.pdf
beginners_python_cheat_sheet_pcc_functions.pdf
GuarachandarChand
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions in Python with all type of arguments
Functions in Python with all type of argumentsFunctions in Python with all type of arguments
Functions in Python with all type of arguments
riazahamed37
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Python functions
Python functionsPython functions
Python functions
ToniyaP1
 
Python functions PYTHON FUNCTIONS1234567
Python functions PYTHON FUNCTIONS1234567Python functions PYTHON FUNCTIONS1234567
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
beginners_python_cheat_sheet_pcc_functions.pdf
beginners_python_cheat_sheet_pcc_functions.pdfbeginners_python_cheat_sheet_pcc_functions.pdf
beginners_python_cheat_sheet_pcc_functions.pdf
GuarachandarChand
 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
 
Ad

Recently uploaded (20)

FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Ad

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
  • 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
  • 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”