Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Chap 4

The document provides an extensive overview of functions in Python, including their definitions, types (built-in and user-defined), syntax, and examples of how to create and use them. It also covers various argument types, variable scopes (global and local), recursion, and the concept of modules for code organization and reuse. Additionally, it discusses advanced topics such as function aliasing, nested functions, and module reloading.

Uploaded by

tokejidnyesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Chap 4

The document provides an extensive overview of functions in Python, including their definitions, types (built-in and user-defined), syntax, and examples of how to create and use them. It also covers various argument types, variable scopes (global and local), recursion, and the concept of modules for code organization and reuse. Additionally, it discusses advanced topics such as function aliasing, nested functions, and module reloading.

Uploaded by

tokejidnyesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Functions

➢ A function is a set of statements that take inputs, do some specific


computation and produces output.
➢ Function is a group of lines which can be reused.
➢ In other languages functions are known as methods, procedures,
subroutines etc
Python supports 2 types of functions
➢ Built in Functions
➢ User Defined Functions
Built in Functions:
➢ The functions which are coming along with Python software
automatically, are called built in functions or pre defined functions.
Ex: id(), type(), input(), eval() …….
Functions
User Defined Functions:
➢ The functions which are developed by programmer explicitly
according to business requirements, are called user defined
functions.
Syntax to Create User defined Functions:

def function_name(parameters) :
“””Your code----
----- and logic”””
return value
Note: While creating functions we use 2 keywords
➢ def (mandatory)
➢ return (optional)
Functions
Write a function to print Hello
def wish():
print("Hello Good Morning")

wish() →Hello Good Morning

➢ We can pass parameters (values) in functions


➢ Parameters are inputs to the function. If a function contains parameters,
then at the time of calling, compulsory we should provide values otherwise
we will get error.
def wish(name):
print("Hello",name," Good Morning")

wish(“Anand") → Hello Anand Good Morning


wish(“Sam") →Hello Sam Good Morning
Function
Write a function to take number as input and print its square value:

def squareIt(x):
print("The Square of",number,"is", x*x)

squareIt(4) →16
squareIt(5) →25

➢ Function can take input values as parameters and executes business


logic, and returns output to the caller with return statement.
Write a Function to accept 2 Numbers as Input and return Sum

def add(x,y):
return x+y
result=add(10,20)
print("The sum is",result) →30
print("The sum is",add(100,200)) →300
Functions
➢ If we are not writing return statement then default return value is None.
def f1():
print("Hello")
f1() #Hello
print(f1()) #Hello
#Hello
➢ Write a Function to check whether the given Number is Even OR Odd?

def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")

even_odd(10) #10 is Even Number


even_odd(15) #15 is Odd Number
Functions
➢ Write a Function to find Factorial of given Number?

def fact(num):
result=1
Output:
while num>=1:
-----------
result=result*num
num=num-1 The Factorial of 1 is : 1
The Factorial of 2 is : 2
return result The Factorial of 3 is : 6
The Factorial of 4 is : 24
for i in range(1,5):
print("The Factorial of",i,"is :",fact(i))
Functions
➢ Returning Multiple Values from a Function:

def sum_sub(a,b):
sum=a+b
Output
sub=a-b
return sum,sub The Sum is : 150
x,y=sum_sub(100,50) The Subtraction is : 50
print("The Sum is :",x)
print("The Subtraction is :",y)
Functions
➢ Returning Multiple Values from a Function:
Ex 2:
def calc(a,b):
sum=a+b Output
sub=a-b
The Results are
mul=a*b 150
div=a/b 50
return sum,sub,mul,div 5000
2.0
t=calc(100,50)
print("The Results are")
for i in t:
print(i)
Functions
Types of Arguments:
There are 4 types of arguments allowed in Python.
➢ Positional Arguments
➢ Keyword Arguments
➢ Default Arguments
➢ Variable Length Arguments
Positional Arguments:
➢ Variables will be assigned in what ever order we assign
def sub(a, b):
print(a-b)
sub(100, 200) #-100
sub(200, 100) #100
➢ Number of parameters and arguments should be same or else we will
get error
Functions
Keyword Arguments:
Output:
Passing values by parameter name. ----------
def wish(name,msg):
Hello Anand Good Morning
print("Hello",name,msg)
Hello Anand Good Morning

wish(name=“Anand",msg="Good Morning")
wish(msg="Good Morning",name=“Anand")

➢ order of arguments is not important but number of arguments


must be matched.
➢ Note: We can use both positional and keyword arguments
simultaneously. But first we have to take positional arguments
and then keyword arguments, otherwise we will get syntaxerror.
Functions
def wish(name,msg):
•wish(“Anand","GoodMorning")
print("Hello",name,msg)
• wish(“Anand",msg="GoodMorning")
# Valid
• wish(name=“Anand”, msg=“Good Morning”)
# Valid
• wish(name="Durga","GoodMorning")
# Valid
#Invalid
Functions
Default Arguments:
➢ we can provide default values for our positional arguments.
➢ If we are not passing any arguments then only default value will
be considered.
def wish(name="Guest"):
print("Hello",name,"Good Morning")
wish(“Anand") #Hello Anand Good Morning
wish() #Hello Guest Good Morning

Note: After default arguments we should not take non default


arguments.
def wish(name="Guest",msg="Good Morning"): #Valid
def wish(name,msg="Good Morning"): #Valid
def wish(name="Guest",msg): #Invalid
Anand Komiripalem
Functions
Variable Length Arguments:
➢ Used for dynamically increasing the arguments
➢ We can call this function by passing any number of arguments
including zero number.
def sum(*n):
total=0
for n1 in n:
total=total+n1
print("The Sum=",total)

sum() #The Sum =0


sum(10) # The Sum =10
sum(10,20) #The Sum =30
sum(10,20,30,40) #The Sum =100
Functions
➢ We can mix variable length arguments with positional arguments.
➢ If we want to take in this way then we need to pass the positional
arguments compulsorily
Ex:
def f1(n1,*s):
result=0
for x in s:
result=result+x
print(n1,”:”result)

f1(“anand”) #anand:0
f1(“anand”,10,20) #anand:30
Anand Komiripalem
Functions
➢ After variable length argument, if we want to provide positional
argument then compulsorily we have to provide those values as
keyword arguments only

def f1(*s, n1):


result=0
for x in s:
result=result+x
print(n1,”:”result)

f1(n1=“anand”) #anand:0
f1(10,20, n1=“anand”) #anand:30
f1(10,20,“anand”) #Error
Functions
We can declare key word variable length in functions
We have to use **n for declaring key- value arguments

def display(**kwargs):
for k,v in kwargs.items():
print(k,"===",v)

display(rno=100,name=“anand", marks=70,subject="Java")

Output:
rno = 100
name = anand
marks = 70
subject = Java
Functions
Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)

f(3,2) → 3 2 4 8

f(10,20,30,40) → 10 20 30 40

f(25,50,arg4=100) → 25 50 4 100

f(arg4=2,arg1=3,arg2=4) →3442

f() →TypeError: f() missing 2 positional arguments: 'arg1' and 'arg2'

f(arg3=10, arg4=20, 30, 40) →SyntaxError: positional argument follows keyword argument

f(4, 5, arg2 = 6) →TypeError: f() got multiple values for argument 'arg2'

f(4, 5, arg3 = 5, arg5 = 6) →TypeError: f() got an unexpected keyword argument 'arg5‘
Functions:Types of Variables
Python supports 2 types of variables.
➢ Global Variables
➢ Local Variables
Global Variables :
➢ The variables which are declared outside of function and are
available to all the functions in a module are global variables
a=10 # global variable
def f1():
print(a)

def f2():
print(a)
f1() #10
f2() #10
Functions: Types of Variables
Local Variables:
➢ The variables which are declared inside a function and are
accessible in that particular function only, such variables are called
as local variables
def f1():
a=10 # local variable
print(a)

def f2():
print(a)

f1() #10
f2() #error
Functions: Types of Variables
a=20
def f1():
a=10 # local variable
print(a)

def f2():
print(a)

f1() #10
f2() #20
Functions: Types of Variables
Global Keyword: To declare global variable inside function

a=10
def f1():
global a
a=777
print(a)

def f2():
print(a)

f1() #777
f2() #777
Functions: Types of Variables
Note: If global variable and local variable having the same name then we can
access global variable inside a function as follows

a = 10 # Global Variable
def f1():
a=777 #Local Variable
print(a)
print(globals()['a'])

f1() #777
#10
Functions: Recursive Functions
➢ A function that calls itself is known as Recursive Function.
➢ Used for reducing the length of the code and improves readability
➢ Complex problems can be solved easily
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result

print("Factorial of 4 is :",factorial(4)) #24


print("Factorial of 5 is :",factorial(5)) #120
Functions: Recursive Functions
Sum of n numbers:

def sumofn(n):
if n==1:
return 1
else:
return n + sumofn(n-1)

sumofn(16) #136
Functions: Recursive Functions
➢ Febinocci Series:
Output:

def f(n): febinocci number: 5


if n<=1: Fibonacci sequence:
return n 0
1
else: 1
return(f(n-1)+f(n-2)) 2
3
nterms = int(input("febinocci number: "))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(f(i))
Functions: Function Aliasing
Function Aliasing:
For the existing function we can give another name, which is nothing
but function aliasing.
def wish(name):
print("Good Morning:",name)
Output:
greeting=wish
print(id(wish)) 46888256
print(id(greeting)) 46888256
Good Morning: Anand
greeting(‘Anand')
Good Morning: Anand
wish(‘Anand')

In the above example only one function is available but we can call that
function by using either wish name or greeting name.
Functions: Nested Function
➢ A function declared inside another function is nothing but nested
functions or inner functions.
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function calling inner function")
inner()
outer() Output:
Inner() → Error
outer function started
outer function calling inner function
inner function execution
error
Functions: Nested Function
➢ In the above example inner() function is local to outer() function and hence
it is not possible to call directly from outside of outer() function.
➢ In order to call a inner function in the outer function then it should be in
return part and then assign it some variable.
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function returning inner function")
return inner
Output:
f1=outer() outer function started
f1() outer function returning inner function
f1()
f1() inner function execution → for f1()
inner function execution → for f1()
inner function execution → for f1()
Functions: Nested Function
What is the difference between the following lines?
f1 = outer and f1 = outer()
➢ In the first case for the outer() function we are providing another name
f1 (function aliasing).
➢ But in the second case we calling outer() function, which returns inner
function. For that inner function() we are providing another name f1

def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function returning inner function")
return inner
f1=outer Output:
f1() outer function started
outer function returning inner function
Modules
Modules
➢ A group of functions, variables and classes saved to a file, which is
nothing but module.
➢ Every Python file (.py) acts as a module.

mymath.py #file name


---------------
x = 200
Y=100
def add(a,b):
print("The Sum:",a+b)

def product(a,b):
print("The Product:",a*b)

➢ The above module contains 2 variables and 2 functions


Modules
➢ If we want to use these variables and functions in other programs
then we need to import them by using “import” module
➢ We can access members by using module name.
modulename.variable
modulename.function()

test.py:
Import mymath
print(mymath.x) #200
mymath.add(10,20) #30
mymath.product(10,20) #200
Modules
Advantages of Modules:
➢ Code Reusability
➢ Improved readability
➢ Improved maintainability

Importing Modules:
➢ Import modulename
➢ from modulename import functions

From mymath import x,add


print(x) #200
add(10,20) #30
product(10,20) #error
Modules
Renaming a module @ time of importing: using aliasing (as)

Import mymath as m
print(m.x) #200
m.add(20,30) #50
m.product(10,20) #200
➢ Once we create an alias name we need to use alias name only,
original name cannot be used, if we try to use the original name we
will get an error
Member Aliasing:

from mymath import x as a, add as sum


print(a) #200
sum(10,30) #40
Modules
Reloading a Module:
➢ By default module will be loaded only once even though we are importing
multiple times.

module1.py:
------------------
print("This is from module1")

test.py
----------
import module1 Output:
import module1
import module1 This is from module1
This is test module
import module1
print("This is test module")
Modules
➢ We can solve this by reloading the module explicitly based on our
requirement
➢ We can reload by using “reload ()” function of “imp” module

import imp
imp.reload(module 1)

Note: Normally import will load the module only once, but some times
while the program is running, the module might be updated and
those will not be reflected in the program. Inorder to apply those
changes in the program then we will need to reload the progam
Modules
Without reload function:
----------------------------------
import time
import module1 Output:
This is from module 1
print(“entering into sleep mode”)
Entering into Sleep Mode
time.sleep(30) Last line printing
import module1
print(“last line printing”)

➢ If we want to get the updated module every time we access it, then we
should go with “reload ” function
Modules
With reload function:
----------------------------------
import time
Output:
from imp import reload
import module1 This is from module 1
print(“entering into sleep mode”) Entering into Sleep Mode
This is from module 1
time.sleep(30) Last line printing
reload(module1)
print(“last line printing”)
Modules
To find members of a module:
dir(): list all members of current module
dir(module_name): lists all members of specified module
Ex: dir(time) #[‘ doc ’, ‘ file ’, ‘ name ’………….]

➢ Every python module will have some special properties for internal
usage which will be assigned at the time of creating the module

Ex: [' annotations ', ' builtins ', ' cached ', ' doc ',
' file ', ' loader ', ' name ', ' package ', ' spec ' ]
Modules
The Special Variable name :

➢ This variable stores information regarding whether the program is


executed as an individual program or as a module.
➢ If the program executed as an individual program then the value of
this variable is main
➢ If the program executed as a module from some other program then
the value of this variable is the name of module where it is defined
➢ by using this name variable we can identify whether the
program is executed directly or as a module.
Modules
multiply.py:
----------------
def mul(a,b):
return a*b
print(mul(5,4)) #20
Print( name ) # main

xyz.py
--------- Output:
Import multiply
20
print(multiply.mul(2,3))
Multiply
print( name ) 6
main
Modules
➢ If we don’t want to print the conditions of a module in other programs
when the module is imported into other programs we should use
name = main
multiply.py:
----------------
def mul(a,b):
return a*b
if name = main :
print(mul(5,4)) #20
Print( name ) # main

xyz.py
---------
Import multiply
print(multiply.mul(2,3)) #6
print( name ) # main
Modules
math module:
➢ Inbulit module
➢ To get functions available in math module use
import math
dir(math)

Ex:
from math import *
print(sqrt(4)) #2.0
print(pi) #3.1415
print(gcd(100,90)) #10

To get the modules available in python


help(‘modules’)
Modules: Random Module
➢ Defines several functions to generate some random values
random(): generates some float value between 0 and 1 excluding the
limits
Output:
0.15720624845042397
from random import * ---------------------------------
print(random()) 0.95433406321847
0.4920568917131689
print(“----------------”) 0.8732940887640129
for i in range(5): 0.7622388235272658
0.6587231098939921
print(random())
0.8573415658967232

randint(x,y): generates some int value between the given numbers


including the limits
Modules: Random Module
from random import * Output:
38
print(randint()) ----
print(“----------------”) 115
180
for i in range(5): 106
print(randint()) 185
167

uniform(): generates some random value between the given limits


excluding the limits
Output:
from random import * 68.63837829312799
print(uniform(1,100)) ---------------------------
161.59909023545111
print("----------------") 120.83689828251825
for i in range(5): 157.53375898087828
172.6639237811024
print(uniform(100,200)) 146.58774382153112
Map Function
• The map() function is used to apply a given function to every
item of an iterable, such as a list or tuple, and returns a map
object (which is an iterator).
• Syntax: map(function, iterable)
Ex1:
fruits = ['apple', 'banana', 'cherry']
res = map(str.upper, fruits)
print(list(res))
o/p-['APPLE', 'BANANA', 'CHERRY']
Ex2:
def f(x):
return x+3
Newlist=list(map(f,range(10)))
Print(newlist)
o/p-[3,4,5,6,7,8,9,10,11,12]
Namespace And Scopes
• Namespace is a collection of different names
• If two names are same and present in same scope then it will cause
name clash,to avoid this name space is used.
• Ex:
module1-display(a,b)
module2-display(c,d)
call-module1.display(10,20)
module2.display(10,20)
Types of Namespace:
1.Global
2.Local
3.In-Built
# var1 is in the global namespace
var1 = 5
def some_func():

# var2 is in the local namespace


var2 = 6
def some_inner_func():

# var3 is in the nested local


# namespace
var3 = 7
Packages
➢ Package is a grouping mechanism or encapsulation mechanism
➢ It is a collection of modules into a single unit, like folder in a system
➢ In order to consider a folder as a package it should contain init .py file
init
➢ From python 3.3 version init .py file is optional to have in a folder
➢ A package can have sub packages in it
Packages
Advantages of Python:
➢ We can resolve naming conflicts
➢ We can identify our components uniquely
➢ Modularity will be improved
➢ Readability will be improved and improvability will be easy

Importing Packages:

Import.package.module_name
Package.module_name.function

(Or)

from package.module_name import function()


function()
Steps to write python package
numpy
• NumPy is a Python library.
• NumPy is used for working with arrays.
• Why numpy?---In Python we have lists that serve the purpose of arrays, but they are
slow to process.
• NumPy aims to provide an array object that is up to 50x faster than traditional Python
lists.
• Installation process:
1.open cmd and type-python –m pip install numpy
2.press enter.
Ex 1:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) o/p:[1 2 3 4 5]
<class 'numpy.ndarray'>
print(type(arr))
matplotlib
• It is a ploting libarary in python and its numerical mathematical extension
is numpy
• It consists of several plots like line,bar,scatter,histogram etc
• Import pyplot module of matplotlib library
• Functions:-
• Plot(a):draw a line with help of data points provided through an array
• Show():displays the drawing on screen
• Bar(x,y)-bar graph
• Scatter(x,y)
• Installation process:
1.open cmd and type-python –m pip install matplotlib
2.press enter
• Ex:
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()
pandas
• Pandas is a Python library.
• Pandas is used to analyze data.
• Pandas is a Python library used for working with data sets.
• It has functions for analyzing, cleaning, exploring, and
manipulating data.
• Pandas are suitable for different kind of data such as-tabular
data,ordered and unordered,arbitrary matrics data.
• 3 data structures used in pandas:
-Series
-Dataframes
-panel
Series-one dimention homogeneous array

• Ex:
import pandas as pd
sr = pd.Series([1000, 5000, 1500, 8222])
print(sr)
o/p:
DataFrame - two-dimensional size-mutable,
heterogeneous tabular data structure
• Ex:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]}
#load data into a DataFrame object:
df = pd.DataFrame(data)
Print(df)
o\p:
calories duration
0 420 50
1 380 40
2 390 45
• Panel-3 dimentional labeled array.mutable
• Syntax:
pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)
Where-
Data takes various forms like
ndarray, series, map, lists, dict,
data
constants and also another
DataFrame

items axis=0

major_axis axis=1

minor_axis axis=2

dtype Data type of each column

copy Copy data. Default, false

You might also like