Python Chap 4
Python Chap 4
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")
def squareIt(x):
print("The Square of",number,"is", x*x)
squareIt(4) →16
squareIt(5) →25
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")
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")
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
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(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
def sumofn(n):
if n==1:
return 1
else:
return n + sumofn(n-1)
sumofn(16) #136
Functions: Recursive Functions
➢ Febinocci Series:
Output:
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.
def product(a,b):
print("The Product:",a*b)
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
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:
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 :
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
Importing Packages:
Import.package.module_name
Package.module_name.function
(Or)
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