Python Functions 1
Python Functions 1
def cube(x):
return x**3
print(cube(2))
def cube(x):
return x**3
result=(cube(2))
print(result)
def cube(x):
return x**3
num=int(input(“Enter a number”))
result=cube(num)
print(“Cube =”,result)
result = multiply(3,9)
print (“product= ”,result)
or
print(multiply(3,9))
evenodd(2)
evenodd(3)
or
num1=int(input(“Enter a number”))
evenodd(num1)
print ( areaofsquare(4))
or
Output
1. Positional arguments
2. Default Arguments
SayHello(‘Tom’)
All the above function calls are valid now, even if the order of
arguments does not match the order of parameters as defined
in the function header.
Returning values from functions
1.Functions returning some value ( non-void functions )
return <value>
❖ a literal
❖ a variable
❖ an expression
for example
def sum(x,y):
s=x+y
return s
result=sum(5,10)
2. Functions not returning any value
(void functions )
The void functions do not return a value but they return a legal
empty value of Python i.e None. Every void function returns
value None to its caller. So if need arises you can assign the
return value somewhere as per your needs .
Consider the above code , None is printed as value stored in a
because greet() returned value None , which is assigned to
variable a.
return<value1/variable1/expression1>,<value2/variabl
e2/expression2>,…
Q. Program to arrange 2 numbers in ascending order using function.
Function returning multiple values.
Function with Default Arguments :Compute area of rectangle.
h.w dt. 09-04-2020
Pass by Object reference.
Recall that everything in Python is an object. So a variable for an object, is actually a
reference to the object. In other words, a variable stores the address where an object
is stored in the memory. It doesn’t contain the actual object itself.
When a function is called with arguments, it is the address of the object stored in the
argument is passed to the parameter variable. However, just for the sake of simplicity,
we say the value of an argument is passed to the parameter while invoking the
function. This mechanism is known as Pass By Value. Consider the following
example:
1 def func(para1):
2 print("Address of para1:", id(para1))
3 print(para1)
4
5 arg1 = 100
6 print("Address of arg1:", id(arg1))
7 func(arg1)
Output:
1 Address of arg1: 1536218288
2 Address of para1: 1536218288
3 100
Notice that the id values are same. This means that
variable arg1 and para1 references the same object. In other words,
both arg1 and para1 points to the same memory location where int object (100) is
stored.
This behavior has two important consequences:
1 def func(para1):
2 para1 += 100 # increment para1 by 100
3 print("Inside function call, para1 =", para1)
4
5 arg1 = 100
6 print("Before function call, arg1 =", arg1)
7 func(arg1)
8 print("After function call, arg1 =", arg1)
Output:
1 def func(para1):
2 para1.append(4)
3 print("Inside function call, para1 =", para1)
4
5 arg1 = [1,2,3]
6 print("Before function call, arg1 =", arg1)
7 func(arg1)
8 print("After function call, arg1 =", arg1)
Output:
1 Before function call, arg1 = [1, 2, 3]
2 Inside function call, para1 = [1, 2, 3, 4]
3 After function call, arg1 = [1, 2, 3, 4]
The code is almost the same, but here we are passing a list to the function instead of
an integer. As the list is a mutable object, consequently changes made by
the func() function in line 2, affects the object pointed to by variable arg1.
1. Global scope
The name declared in top level segment (_main_) of a program is
said to have global scope and is usable inside the whole program
and all blocks( functions, other blocks) contained within the
program.
2. Local scope
The name declared in a function body is said to have local scope
i.e., it can be use only within this function and other blocks
contained under it. The names of formal arguments also have
local scope.
Scope Example 1
Global Variables : Variable defined outside all functions are
global variables.
x=5
def func(a):
b=a+1
return b
y = input(“Enter number”)
z = y + func (x)
print (z)
Scope Example 2 :
Name resolution ( Resolving Scope of a name )
For every name reference within a program i.e., when you access a
variable from within a program or function, Python follows name
resolution rule, also known as LEGB rule.
def calcsum(x,y):
s=x+y
print(num1)
return s
greet()
This would return error as name is neither in local environment nor in global
environment.
def state1( ) :
tigers =15
print ( tigers )
tigers = 95
print tigers
state1( )
print ( tigers )
Output :
95
15
95
That means a local variable created with same name as that of global variable ,
hides the global variable. As in above code , local variable tigers hides global
variable tigers in function state1( )
def state1( ) :
global tigers #This is an indication not to create local
tigers = 15 variable with the name tigers, rather use
print ( tigers ) global variable tigers.
tigers = 95
print tigers
state1( )
print ( tigers )
Output
95
15
15
Output:
key: a Value: 1
key: b Value: 2
key: c Value: 3
In the code given below we pass given dictionary as an argument to a python function and then call the
function which works on the keys/value pairs and gives the result accordingly
Example
d = {'a' : 1, 'b' : 2, 'c' : 3}
def f(dict):
for k, v in dict.iteritems():
print k, 2*v
f(d)
Output
a 2
c 6
b 4
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error :
Conclusion
1. Mutable and immutable objects are handled differently in python.
Immutable objects are quicker to access and are expensive
to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.
We have to define a function that will accept string argument and print it. Here, we
will learn how to pass string value to the function?
Example:
Input:
str = "Hello world"
Function call:
printMsg(str)
Output:
"Hello world"
Program:
# Main code
# function calls
printMsg("Hello world!")
printMsg("Hi! I am good.")
Output
Hello world!
Hi! I am good.
Write function that will accept a string and return total number of vowels
# function definition: it will accept
# a string parameter and return number of vowels
def countVowels(str):
count = 0
for ch in str:
if ch in "aeiouAEIOU":
count +=1
return count
# Main code
# function calls
str = "Hello world!"