Function
Function is a block of code that perform a particular task
It only runs when it is invoked or called.
You can pass data, known as parameters, into a function.
A function can return data as a result using return keyword.
Types of functions
1. User Defined : defined by the user using def keyword
2. built-in functions: Predefined function in python language
Creating/Defining Function:
def my_function():
print("Hello from a function")
Calling Function
my_function()
Parameters(arguments): information passed in a function during creation or calling is called parameters.
def sum(a,b):
s=a+b
print(s)
x=10
y=20
sum(x,y)
# a , b and x,y are called parameters.
Actual parameters: parameters passed in function calling. In above code x and y are actual parameters
Formal parameters: parameters passed in function definition. In above code a and b are formal parameters
Function return value using return keyword
def sum(a,b):
s=a+b
return s
x=10
y=20
n=(x,y)
print(n)
A function can return multiple values
# This function returns a tuple
def fun():
str = "ajay"
x = 20
return str, x; # Return tuple, we could also write (str, x)
str, x = fun() # Assign returned tuple
print(str)
print(x)
A function can return multiple values using list or tuple or dictionary
# This function returns a tuple
def fun():
str = "mukesh"
x = 20
return str, x; # Return tuple, we could also write (str, x)
t = fun() # Assign returned tuple
print(t)
output:
('mukesh', 20)
# This function returns a dictionary
def fun():
d = dict();
d['str'] = "abc"
d['x'] = 20
return d
# Driver code to test above method
d = fun()
print(d)
# This function returns a list
def fun():
str = “abc"
x = 20
return [str, x];
# Driver code to test above method
list = fun()
print(list)
Variable length argument:
We can pass any number of arguments in a functon using * symbol.
# sum of n mumbers using variable length arguments with function
def sum(*n):
m=n[0]
for i in n:
s=s+i
print(s)
sum(2,5,6)
sum(12,15,6)
sum(22,5,6,2.5)
#Find largest number among given numbers
def maximum(*n):
m=0
for i in n:
if(i>m):
m=i
return m
print(maximum(1,2,3,4)) # 4
print(maximum(11,22,3,934,66,77,88,555)) #555
print(maximum(111,2,3,4,66,7,8,555,33)) #555
Function with Default Arguments
Default Arguments: Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.
If we don’t pass any value to the function then it will take a pre defined value.
def hello(name, msg = "Good morning!"):
print("Hello",name + ', ' +msg)
hello("mukesh")
hello("Modi","How do you do?")
Note
->Any number of arguments in a function can have a default value.
->non-default arguments cannot follow default arguments.
For example, if we had defined the function header above
def hello(msg = "Good morning!", name):
SyntaxError: non-default argument follows default argument
Positional Arguments
We cannot change the position of arguments.
if change the output will be changed.
def sub(a,b):
print(a-b)
sum(20,35) # 20 will be assigned in a and 35 will be assigned in b
sum(35,20) # 35 will be assigned in a and 20 will be assigned in b
Keyword Arguments
When we Call above function with their arguments name . Then we need not to remember the position of arguments
ef sub(a,b):
print(a-b)
sum(a=20,b=35) # 20 will be assigned in a and 35 will be assigned in b
sum(n=35, a=20) # 35 will be assigned in a and 20 will be assigned in b
output
-15
-15
Scope of Variable:
Part of program where a variable is visible or accessible
Local :
Variable declared in side the function called local variable
With local scope, variable can be used in the function where it is declared
def fun():
a=10
print(a) # a is local variable
fun()
Global:
Variable declared outside of all function called global variable
With global scope , variable can be used or accessed any where in the program
b=20 # global variable
def fun():
a=10 # local variable
print(a)
print(b)
fun()
output
10
20
global keyword
If we want to change the value of global variable inside the function we have to use global keyword
It is used to create global variables from a non-global scope i.e inside a function.
It is used When we want to do assign value to global variable inside function.
We can access or print global variable any where in program without using global keyword
b=20
def fun():
a=10
print(a) # a is local variable
print(b) # b is a global variable can be access any where in the program
fun()
print(b)
ouput:
10
20
20
When we change the value of global variable inside local scope. global keyword is used
b=20
def fun():
a=10
print(a)
global b
b=b+5
fun()
print(b)
output
10
25
Mutable vs Immutable Objects in Python
Python represents all its data as objects . every object can be either mutable or immutable based on the type of data they hold.
Every variable in python holds an instance of an object.
There are two types of objects in python i.e. Mutable and Immutable objects.
Generally Primitive-like types are probably immutable and Customized Container-like types are mostly mutable.
Mutable object are changeable while Immutable are not changeable
Mutable objects
Can change their state or contents.
These are of type like list, dict, set . Custom classes
Use of mutable objects is recommended when there is a need to change the size or content of the object.
# Python code to test that lists are mutable
color = ["udaigiri", "arawali", "shivalik"]
print(color)
color[0] = "Neelgiri"
color[-1] = "Holinding-2"
print(color)
Output without error
["Neelgiri", "arawali", "Holinding-2"]
Immutable Objects :
These are of in-built types like int, float, bool, string, unicode, tuple.
An immutable object can’t be changed after it is created.
Whenever an object is instantiated, it is assigned a unique object id.
Defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object.
Quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.
e.g
# Python code to test that tuples are immutable
t = (1, 2, 3,4)
t[0] = 4
print(t)
Give TypeError: 'tuple' object does not support item assignment
e.g Python code to test that strings are immutable
message = "Welcome to Meraprayas"
message[0] = 'p'
print(message)
TypeError: 'str' object does not support item assignment
Important Fact
Consider a tuple
tuple = ([1, 2, 3], 'meraprayas')
The tuple consists of a string and a list.
Strings are immutable so we can’t change its value.
But the contents of the list can change.
The tuple itself isn’t mutable but contain items that are mutable.
Passing a List as an Argument
def houses(house):
for x in house:
print(x)
house = ["udaigiri", "arawali", "shivalik","Neelgiri","H-1","H-2"]
houses(house)
output:
udaigiri
arawali
shivalik
Neelgiri
H-1
H-2
Passing a Dictionary as an Argument
A dictionary in Python is a collection of data which is unordered and mutable.
# A function that takes dictionary as an argument
def func(d):
for key in d:
print("key:", key, "Value:", d[key])
# Driver's code
D = {'one':1, 'two':2, 'three':3,"four":4}
func(D)
Output
key: one Value: 1
key: two Value: 2
key: three Value: 3
key: four Value: 4
Conclusion
Local variable : Variable declared inside function
Global variable: Variable declared outside of all functions
global keyword: Used to change the value of global variable in local scope
Mutable object: can be changed after creation. E.g list,dictionary, set, custom classes
Immutable objects: can not change after creation e.g tuple, int, bool, string etc
Question
Q. When writing a function in Python, do we have to place all keyword arguments so that they come after all the positional arguments in the function definition?
Answer
Yes, keyword arguments, which are assigned some value in the definition, must be written after all the positional arguments. If we do not follow this rule, then Python will give us an error message.
Example code
# This would cause an error, because arg1 is a keyword argument but was placed before arg2, a positional argument.
def func(arg1=10, arg2, arg3=30):
return arg1 + arg2 + arg3
print(func(20))
# All keyword arguments must follow all the positional arguments, so this updated function would work.
def fixed_func(arg2, arg1=10, arg3=30):
return arg1 + arg2 + arg3
print(fixed_func(20)) # This will print 60
Is Python call by reference or call by value
When you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function.
Whereas passing mutable objects can be considered as call by reference because when their values are changed inside the function, then it will also be reflected outside the function.
# Python code to demonstrate call by value
string = "Hello"
def test(string):
string = "Bye"
print("Inside Function:", string)
# Driver's code
test(string)
print("Outside Function:", string)
Output
Inside Function: Bye
Outside Function: Hello
# Python code to demonstrate call by reference
def add_more(list):
list.append(50)
print("Inside Function", list)
# Driver's code
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
Output
Inside Function [10, 20, 30, 40, 50]
Outside Function: [10, 20, 30, 40, 50]