SlideShare a Scribd company logo
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
Python programming workshop session 4
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.
Python programming workshop session 4
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

More Related Content

PPTX
Python workshop session 6
PPTX
Python programming workshop session 2
PPTX
Python programming workshop session 1
PPTX
Python programming workshop session 3
PPTX
Advance python programming
PPT
C++ Language
PPTX
Intro to c++
Python workshop session 6
Python programming workshop session 2
Python programming workshop session 1
Python programming workshop session 3
Advance python programming
C++ Language
Intro to c++

What's hot (20)

PDF
Chapter 1 Basic Programming (Python Programming Lecture)
PPTX
Introduction to C++
PPTX
Python Programming Essentials - M17 - Functions
PPTX
10. Recursion
PDF
Python unit 2 as per Anna university syllabus
PPSX
C++ Programming Language
DOCX
Maharishi University of Management (MSc Computer Science test questions)
PDF
Thinking in Functions: Functional Programming in Python
PPT
Basics of c++ Programming Language
PPT
C++ programming
PDF
Cbse marking scheme 2006 2011
PPTX
09. Methods
PPTX
GE8151 Problem Solving and Python Programming
PPTX
12. Exception Handling
PDF
Programming Fundamentals Decisions
PDF
Functional programming in Python
PPTX
03. Operators Expressions and statements
PPT
C++ functions presentation by DHEERAJ KATARIA
PDF
Java Programming Workshop
Chapter 1 Basic Programming (Python Programming Lecture)
Introduction to C++
Python Programming Essentials - M17 - Functions
10. Recursion
Python unit 2 as per Anna university syllabus
C++ Programming Language
Maharishi University of Management (MSc Computer Science test questions)
Thinking in Functions: Functional Programming in Python
Basics of c++ Programming Language
C++ programming
Cbse marking scheme 2006 2011
09. Methods
GE8151 Problem Solving and Python Programming
12. Exception Handling
Programming Fundamentals Decisions
Functional programming in Python
03. Operators Expressions and statements
C++ functions presentation by DHEERAJ KATARIA
Java Programming Workshop
Ad

Similar to Python programming workshop session 4 (20)

PDF
Unit-2 Introduction of Modules and Packages.pdf
PPTX
Chapter1 python introduction syntax general
PDF
class 12 Libraries in dfbdsbsdbdfbdfdfdf.pdf
PDF
Introduction to Python for Plone developers
PDF
An overview on python commands for solving the problems
PPTX
Introduction to Python External Course !!!
PPTX
Introduction to Python Programming
PPT
Python Training v2
PPTX
Python knowledge ,......................
PPTX
Docketrun's Python Course for beginners.pptx
PDF
Using Python Libraries.pdf
PPTX
Python for Beginners
DOCX
Modules in Python.docx
PPT
Python scripting kick off
PDF
Introduction to Python Programming | InsideAIML
PPTX
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
PDF
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
PPTX
Module-1.pptx
PDF
ch 2. Python module
PPTX
Python_ppt for basics of python in details
Unit-2 Introduction of Modules and Packages.pdf
Chapter1 python introduction syntax general
class 12 Libraries in dfbdsbsdbdfbdfdfdf.pdf
Introduction to Python for Plone developers
An overview on python commands for solving the problems
Introduction to Python External Course !!!
Introduction to Python Programming
Python Training v2
Python knowledge ,......................
Docketrun's Python Course for beginners.pptx
Using Python Libraries.pdf
Python for Beginners
Modules in Python.docx
Python scripting kick off
Introduction to Python Programming | InsideAIML
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Module-1.pptx
ch 2. Python module
Python_ppt for basics of python in details
Ad

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Business Ethics Teaching Materials for college
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Cell Types and Its function , kingdom of life
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Pre independence Education in Inndia.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
O7-L3 Supply Chain Operations - ICLT Program
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Business Ethics Teaching Materials for college
FourierSeries-QuestionsWithAnswers(Part-A).pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
VCE English Exam - Section C Student Revision Booklet
Cell Types and Its function , kingdom of life
2.FourierTransform-ShortQuestionswithAnswers.pdf
Anesthesia in Laparoscopic Surgery in India
Pre independence Education in Inndia.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
human mycosis Human fungal infections are called human mycosis..pptx
TR - Agricultural Crops Production NC III.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf

Python programming workshop session 4

  • 1. 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
  • 2. 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)
  • 3. 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
  • 4. 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!
  • 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 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
  • 7. 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
  • 8. 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
  • 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 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.
  • 11. 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 *
  • 13. 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.
  • 14. 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
  • 15. 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))
  • 16. 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)
  • 17. Think Big with Python
  • 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 "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
  • 21. 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.
  • 22. 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.
  • 24. 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
  • 25. 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
  • 26. 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​
  • 27. • 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
  • 28. • 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
  • 29. • 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
  • 30. 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