KEMBAR78
Python programming workshop session 4 | PPTX
Faculty of Engineering Science & Technology(FEST)
Hamdard Institute of Engineering Technology(HIET)
HAMDARD UNIVERSITY
Instructor
ABDUL HASEEB
HANDS-ON WORKSHOP ON PYTHON
PROGRAMMING LANGUAGE
Faculty Development Program (Session-10)
DAY-4
Function
A piece code which is written several time doing the
same job take more lines in program and make
code complex to read. To make program simple and
reduce lines a Function can be used.
Syntax
#function definition
def function_name( parameters ):
……….function code
……….return [expression]
#calling the function
function_name( parameter)
Why to use Function
Program without Function
a=1
b=2
print(a+b)
a=3
b=4
print(a+b)
a=5
b=6
print(a+b)
a=7
b=8
print(a+b)
a=9
b=10
print(a+b)
Program with Function
def add(num1,num2): #Function of add
ans = num1 + num2
return ans #Function ends here
print(add(1,2))
print(add(3,4))
print(add(5,6))
print(add(7,8))
print(add(9,10))
Output
3 7 11 15 19
Function with no Argument no Return
Program
import time
from time import sleep
from time import gmtime, strftime
def get_time():
print("-----CLOCK-----")
print(strftime("Date is %Y-%m-%d ", gmtime()))
print(strftime("Time is %H:%M:%S", gmtime()))
return
print("""This is data and Time program
Press 'Ctrl = c' to exit""")
try:
while True:
get_time()
sleep(1)
except KeyboardInterrupt:
print("Thank you!")
Output
This is data and Time program
Press 'Ctrl = c' to exit
-----CLOCK-----
Date is 2017-08-09
Time is 18:28:58
-----CLOCK-----
Date is 2017-08-09
Time is 18:28:59
-----CLOCK-----
Date is 2017-08-09
Time is 18:29:01
-----CLOCK-----
Date is 2017-08-09
Time is 18:29:02
Thank you!
Program
import calendar
def get_month_calendar(year,month):
cal = calendar.month(year,month)
print (cal)
return
year = int(input("Enter year = "))
month = int(input("Enter month = "))
get_month_calendar(year,month)
Function with Argument but No Return
Output
Enter year = 2017
Enter month = 8
August 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Function with Argument and Return
Program
import calendar
day =
["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
def get_week_day(date,month,year):
a = calendar.weekday(year,month,date)
return a
year = int(input("Enter year = "))
month = int(input("Enter month = "))
date = int(input("Enter date = "))
result = get_week_day(date,month,year)
print("The day of ", year,'-',month,'-',date,'is' ,day[result])
Output
Enter year = 2017
Enter month = 8
Enter day = 10
The day of 2017 - 8 - 10 is Thursday
Function Exercise
Write a program of name “code1” having
functions ‘add’ and ‘sub’
Write another program of name “code2” having
‘mul’ and ‘div’.
The program passes 2 numbers as argument and
function calculate and return its result
Function Exercise program 1
Program
def add(num1,num2):
ans = num1 + num2
return ans
def sub(num1,num2):
ans = num1 - num2
return ans
a = 5
b = 2
print(a,'+',b,'=',add(a,b))
print(a,'-',b,'=',sub(a,b))
Output
5 + 2 = 7
5 - 2 = 3
Program
def mul(num1,num2):
ans = num1 * num2
return ans
def div(num1,num2):
ans = num1 / num2
return ans
a = 5
b = 2
print(a,'x',b,'=',mul(a,b))
print(a,'/',b,'=',div(a,b))
Result:
5 x 2 = 10
5 / 2 = 2.5
Function Exercise program 2
Module
• A module allows you to logically organize your
Python code. Grouping related code into a
module makes the code easier to understand and
use. A module is a Python object with arbitrarily
named attributes that you can bind and
reference.
• Simply, a module is a file consisting of Python
code. A module can define functions, classes and
variables. A module can also include runnable
code.
Import Module to program
• The import Statement
Import the Module
Syntax:
import module1[, module2[,... moduleN]
• The from...import Statement
Import functions from Module
Syntax:
from modname import name1[, name2[, ... nameN]]
• The from...import * Statement
Import all functions from Module
Syntax:
from modname import *
Module
Locating Modules
When you import a module, the Python interpreter
searches for the module in the following sequences −
•The current directory.
•If the module is not found, Python then searches each
directory in the shell variable PYTHONPATH.
•If all else fails, Python checks the default path. On UNIX,
this default path is normally /usr/local/lib/python3/.
The module search path is stored in the system module
sys as the sys.path variable. The sys.path variable
contains the current directory, PYTHONPATH, and the
installation-dependent default.
Executing Modules as Scripts
Use the following line in the program
Syntax of program for use as Module
Functions are here
if __name__ == "__main__":
Main program is here
Making program as Python Scripts
Code 1
def add(num1,num2):
ans = num1 + num2
return ans
def sub(num1,num2):
ans = num1 - num2
return ans
if __name__ == '__main__':
a = 5
b = 2
print(a,'+',b,'=',add(a,b))
print(a,'-',b,'=',sub(a,b))
Code 2
def mul(num1,num2):
ans = num1 * num2
return ans
def div(num1,num2):
ans = num1 / num2
return ans
if __name__ == '__main__':
a = 5
b = 2
print(a,'x',b,'=',mul(a,b))
print(a,'/',b,'=',div(a,b))
Importing Module program
import code1 #import code1 Module
import code12 #import code2 Module
result = code1.add(4,5)
print(result)
result = code2.mul(4,5)
print(result)
from code1 import add,sub #Import add and Sub Function
from code2 import * # Import all Function
result = add(3,5)
print(result)
result = sub(5,2)
print(result)
result = mul(2,5)
print(result)
result = div(5,2)
print(result)
Think Big with Python
Numpy-Python
NumPy (pronounced (NUM-py) is a library for
the Python programming language, adding
support for large, multi-dimensional arrays
and matrices, along with a large collection of
high-level mathematical functions to operate
on these arrays
SciPy-Python
SciPy (pronounced "Sigh Pie”) is an open source Python library
used for scientific computing and technical computing.
SciPy contains modules for
•Optimization
•linear algebra
•Integration
•Interpolation
•special functions
•FFT, signal
•image processing,
•Ordinary differential equation solvers
Pandas-Python
Pandas is a software library for the Python
programming language used for data
manipulation and analysis. In particular, it
offers data structures and operations for
manipulating numerical tables and time
series.
Matplotlib Python
• matplotlib is a plotting library for the Python
programming language and its numerical
mathematics extension NumPy.
• designed to closely resemble that of MATLAB,
though its use is discouraged. SciPy makes use
of matplotlib.
Installing Package
pip is a package management system used to
install and manage software packages written
in Python. Many packages can be found in the
Python Package Index (PyPI)
• pip search package-name
• pip download package-name
• pip install package-name
• pip uninstall package-name
Example of Install Python Package
using PIP Step # 1
• Installing openCV package in Python 3.6 IDLE on Windows 7
• Step # 1 Search Python 3.6 path in the start menu
• For Windows 7 or XP:
• Right click on IDLE 3.6 Icon, Click on Properties This is shown in the
following image
Example of Install Python Package
using PIP Step # 2
• The window of IDLE Property opens.
• Copy the address from "Start in"
textbox
• This is shown in the following image
• Copy only till C:........Python37-32
E.g:
• C:UsersHomeAppDataLocalProgra
msPythonPython37-32​
• Open Command Prompt by typing CMD in
"serach program" file box in start windows button
• Goto C Directory by typing C:
• write cd and paste the copy address of Pyhton 3.6
IDLE Installation path
• Write cd scripts to go the Scripts folder
• This is shown in the following image
Example of Install Python Package
using PIP Step # 3
• Search openCV package using following
command
pip search opencv
• show in the Red box
• found Opencv package in Yellow box
Example of Install Python Package
using PIP Step # 4
• Install opencv-python using PIP-install command
pip install opencv-python
• This is shown in the following image. Just type
and enter all the reset of work done by PIP itself
Example of Install Python Package
using PIP Step # 5
Check the proper installation
• Open Python IDLE and write the following command
• 1) import cv2
• 2) import numpy
• 3) print(cv2.__version__)
• 3.4.2
• If no error occur then installation has done properly
Example of Install Python Package
using PIP Step # 6
Thank you

Python programming workshop session 4

  • 1.
    Faculty of EngineeringScience & Technology(FEST) Hamdard Institute of Engineering Technology(HIET) HAMDARD UNIVERSITY Instructor ABDUL HASEEB HANDS-ON WORKSHOP ON PYTHON PROGRAMMING LANGUAGE Faculty Development Program (Session-10) DAY-4
  • 2.
    Function A piece codewhich is written several time doing the same job take more lines in program and make code complex to read. To make program simple and reduce lines a Function can be used. Syntax #function definition def function_name( parameters ): ……….function code ……….return [expression] #calling the function function_name( parameter)
  • 3.
    Why to useFunction Program without Function a=1 b=2 print(a+b) a=3 b=4 print(a+b) a=5 b=6 print(a+b) a=7 b=8 print(a+b) a=9 b=10 print(a+b) Program with Function def add(num1,num2): #Function of add ans = num1 + num2 return ans #Function ends here print(add(1,2)) print(add(3,4)) print(add(5,6)) print(add(7,8)) print(add(9,10)) Output 3 7 11 15 19
  • 4.
    Function with noArgument no Return Program import time from time import sleep from time import gmtime, strftime def get_time(): print("-----CLOCK-----") print(strftime("Date is %Y-%m-%d ", gmtime())) print(strftime("Time is %H:%M:%S", gmtime())) return print("""This is data and Time program Press 'Ctrl = c' to exit""") try: while True: get_time() sleep(1) except KeyboardInterrupt: print("Thank you!") Output This is data and Time program Press 'Ctrl = c' to exit -----CLOCK----- Date is 2017-08-09 Time is 18:28:58 -----CLOCK----- Date is 2017-08-09 Time is 18:28:59 -----CLOCK----- Date is 2017-08-09 Time is 18:29:01 -----CLOCK----- Date is 2017-08-09 Time is 18:29:02 Thank you!
  • 5.
    Program import calendar def get_month_calendar(year,month): cal= calendar.month(year,month) print (cal) return year = int(input("Enter year = ")) month = int(input("Enter month = ")) get_month_calendar(year,month) Function with Argument but No Return Output Enter year = 2017 Enter month = 8 August 2017 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
  • 6.
    Function with Argumentand Return Program import calendar day = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] def get_week_day(date,month,year): a = calendar.weekday(year,month,date) return a year = int(input("Enter year = ")) month = int(input("Enter month = ")) date = int(input("Enter date = ")) result = get_week_day(date,month,year) print("The day of ", year,'-',month,'-',date,'is' ,day[result]) Output Enter year = 2017 Enter month = 8 Enter day = 10 The day of 2017 - 8 - 10 is Thursday
  • 7.
    Function Exercise Write aprogram of name “code1” having functions ‘add’ and ‘sub’ Write another program of name “code2” having ‘mul’ and ‘div’. The program passes 2 numbers as argument and function calculate and return its result
  • 8.
    Function Exercise program1 Program def add(num1,num2): ans = num1 + num2 return ans def sub(num1,num2): ans = num1 - num2 return ans a = 5 b = 2 print(a,'+',b,'=',add(a,b)) print(a,'-',b,'=',sub(a,b)) Output 5 + 2 = 7 5 - 2 = 3
  • 9.
    Program def mul(num1,num2): ans =num1 * num2 return ans def div(num1,num2): ans = num1 / num2 return ans a = 5 b = 2 print(a,'x',b,'=',mul(a,b)) print(a,'/',b,'=',div(a,b)) Result: 5 x 2 = 10 5 / 2 = 2.5 Function Exercise program 2
  • 10.
    Module • A moduleallows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. • Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
  • 11.
    Import Module toprogram • The import Statement Import the Module Syntax: import module1[, module2[,... moduleN] • The from...import Statement Import functions from Module Syntax: from modname import name1[, name2[, ... nameN]] • The from...import * Statement Import all functions from Module Syntax: from modname import *
  • 12.
  • 13.
    Locating Modules When youimport a module, the Python interpreter searches for the module in the following sequences − •The current directory. •If the module is not found, Python then searches each directory in the shell variable PYTHONPATH. •If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python3/. The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
  • 14.
    Executing Modules asScripts Use the following line in the program Syntax of program for use as Module Functions are here if __name__ == "__main__": Main program is here
  • 15.
    Making program asPython Scripts Code 1 def add(num1,num2): ans = num1 + num2 return ans def sub(num1,num2): ans = num1 - num2 return ans if __name__ == '__main__': a = 5 b = 2 print(a,'+',b,'=',add(a,b)) print(a,'-',b,'=',sub(a,b)) Code 2 def mul(num1,num2): ans = num1 * num2 return ans def div(num1,num2): ans = num1 / num2 return ans if __name__ == '__main__': a = 5 b = 2 print(a,'x',b,'=',mul(a,b)) print(a,'/',b,'=',div(a,b))
  • 16.
    Importing Module program importcode1 #import code1 Module import code12 #import code2 Module result = code1.add(4,5) print(result) result = code2.mul(4,5) print(result) from code1 import add,sub #Import add and Sub Function from code2 import * # Import all Function result = add(3,5) print(result) result = sub(5,2) print(result) result = mul(2,5) print(result) result = div(5,2) print(result)
  • 17.
  • 18.
    Numpy-Python NumPy (pronounced (NUM-py)is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
  • 20.
    SciPy-Python SciPy (pronounced "SighPie”) is an open source Python library used for scientific computing and technical computing. SciPy contains modules for •Optimization •linear algebra •Integration •Interpolation •special functions •FFT, signal •image processing, •Ordinary differential equation solvers
  • 21.
    Pandas-Python Pandas is asoftware library for the Python programming language used for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series.
  • 22.
    Matplotlib Python • matplotlibis a plotting library for the Python programming language and its numerical mathematics extension NumPy. • designed to closely resemble that of MATLAB, though its use is discouraged. SciPy makes use of matplotlib.
  • 24.
    Installing Package pip isa package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index (PyPI) • pip search package-name • pip download package-name • pip install package-name • pip uninstall package-name
  • 25.
    Example of InstallPython Package using PIP Step # 1 • Installing openCV package in Python 3.6 IDLE on Windows 7 • Step # 1 Search Python 3.6 path in the start menu • For Windows 7 or XP: • Right click on IDLE 3.6 Icon, Click on Properties This is shown in the following image
  • 26.
    Example of InstallPython Package using PIP Step # 2 • The window of IDLE Property opens. • Copy the address from "Start in" textbox • This is shown in the following image • Copy only till C:........Python37-32 E.g: • C:UsersHomeAppDataLocalProgra msPythonPython37-32​
  • 27.
    • Open CommandPrompt by typing CMD in "serach program" file box in start windows button • Goto C Directory by typing C: • write cd and paste the copy address of Pyhton 3.6 IDLE Installation path • Write cd scripts to go the Scripts folder • This is shown in the following image Example of Install Python Package using PIP Step # 3
  • 28.
    • Search openCVpackage using following command pip search opencv • show in the Red box • found Opencv package in Yellow box Example of Install Python Package using PIP Step # 4
  • 29.
    • Install opencv-pythonusing PIP-install command pip install opencv-python • This is shown in the following image. Just type and enter all the reset of work done by PIP itself Example of Install Python Package using PIP Step # 5
  • 30.
    Check the properinstallation • Open Python IDLE and write the following command • 1) import cv2 • 2) import numpy • 3) print(cv2.__version__) • 3.4.2 • If no error occur then installation has done properly Example of Install Python Package using PIP Step # 6
  • 31.