Unit Ii (Notes-2)
Unit Ii (Notes-2)
Unit Ii (Notes-2)
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.functions are further
classified into 4 types
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
return expression
1
example:
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
Types of Functions in Python:
• Anonymous functions, which are also called lambda functions because they
are not declared with the standard def keyword.
2
o In above code execution of the code is Line 1 2 3. If order is not same the
code will produce error.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Parameters:
Example:
def sum(a,b):
print(a+b)
sum(1,2)
Arguments:
Example:
def sum(a,b):
print(a+b)
sum(1,2)
Output:
3
Function Arguments in Python
Earlier, you learned about the difference between parameters and arguments. In
short, arguments are the things which are given to any function or method call, while
the function or method code refers to the arguments by their parameter names.
There are four types of arguments that Python UDFs can take:
1.Default arguments
2.Required arguments
3.Keyword arguments
1.Default Arguments:
Default arguments are those that take a default value if no argument value is passed
during the function call. You can assign this default value by with the assignment
operator =, just like in the following example:
Example1:
def add(a=1,b=5,c=8):
print(“add=”,(a+b+c))
add(10)
output:
23
Example 2:
Def add(a=1,b=5,c=8):
print(“add=”,(a+b+c))
add(10,20,30)
output:
60
4
2.Required Arguments
These are the arguments which are required to be passed at the time of function calling
with the exact match of their positions in the function call and function definition. If
either of the arguments is not provided in the function call, or the position of the
arguments is changed, the Python interpreter will show the error.
Example 1
def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))
Output:
Enter the name: John
Hi John
Example2:
def test(i,j):
Print(“i=”,I,”j=”,j)
test(10,20)
Test(20,10)
Output:
i=10 j=20
i=20 j=10
3.Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function
call will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function
calling and definition. If the same match is found, the values of the arguments are
copied in the function definition.
Example 1
#function func is called with the name and message as the keyword arguments
5
def func(name,message):
print("printing the message with",name,"and ",message)
#name and message is copied with the values John and hello respectively
func(name = "John",message="hello")
Output:
printing the message with John and hello
#The function simple_interest(p, t, r) is called with the keyword arguments the order of
arguments #doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:
If we provide the different name of arguments at the time of function call, an error will
be thrown.
Example 3
def simple_interest(p,t,r):
return (p*t*r)/100
# doesn't find the exact match of the name of the arguments (keywords)
6
Output:
In large projects, sometimes we may not know the number of arguments to be passed
in advance. In such cases, Python provides us the flexibility to offer the comma-
separated values which are internally treated as tuples at the function call. By using the
variable-length arguments, we can pass any number of arguments.
Example
def printme(*names):
print(name)
printme("john","David","smith","nick")
Output:
john
David
smith
nick
7
Python Modules
Syntax:
import module
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path.
Note: This does not import the functions or classes directly instead imports
the module only. To access the functions inside the module the dot(.) operator
is used.
print(calc.add(10, 2))
Python’s from statement lets you import specific attributes from a module
without importing the module as a whole.
8
Example: Importing specific attributes from the module
4.0
720
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops,
and function calls.
9
• Repetition - used for looping, i.e., repeating a piece of code multiple times
Conditional statements or Selection/Decision control statements
n = 10
if n % 2 == 0:
10
output:
n is an even number
n = 5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
Output
n is odd
11
a = 5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")
output:
c is big
y = 12
if x == y:
elif x > y:
else:
output:
x is greater than y
Iteration or control statements:
A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement –
1.while loop
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
13
Syntax
while expression:
statement(s)
Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
When the above code is executed, it produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
14
The block here, consisting of the print and increment statements, is executed
repeatedly until count is no longer less than 9. With each iteration, the current
value of the index count is displayed and then increased by 1.
2.For Loop:
It has the ability to iterate over the items of any sequence, such as a list or a
string.
Syntax
for iterating_var in sequence:
statements(s)
Example
#!/usr/bin/python
15
print 'Current fruit :', fruit
print "Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
An alternative way of iterating through each item is by index offset into the
sequence itself. Following is a simple example –
Here, we took the assistance of the len() built-in function, which provides the total
number of elements in the tuple as well as the range() built-in function to give us
the actual sequence to iterate over.
16
Example
Print all numbers from 0 to 5, and print a message when the loop has
ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a
break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3:break
print(x)
else:
print("Finally finished!")
Example
Exit the loop when i is 3:
i = 1
17
while i < 6:
print(i) 19
if i == 3:
break
i += 1
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Pass statement:
18
If we want to implement the code in the future and now it should not be
empty, If we place empty for loop then the interpreter throws an error, to
prevent such type of errors pass will be used.
The pass statement constructs the body of the for loop that does nothing
Syntax:
The function which return any value are called as fruitful function.
The function which does not return any value are called as void function.
Fruitful functions means the function that gives result or return values after
execution.
Some functions gets executed but doesn’t return any value.
While writing fruitful functions we except a return value and so we must assign
it to a variable to hold return value.
In void function you can display a value on screen but cannot return a value.
A void function may or may not have return statement, if void function has
return statement then it is written without any expression
19
def fun1():
print("Python")
print("ITVoyagers")
return
fun1(5,2)
In above example main function have passed values to given function and as
print statement is used function will not return anything it will just print value.
return a+b
print(fun2(5,8))
In above example we have passed two values to the given function which then
returns sum of that values to main function using return keyword.
>>> math.sqrt(6)
2.449489742783178
20
In script mode above function does not return a value and becomes of no use.
import math
math.sqrt(6)
Return statement
Return statement is used in a function to return some value to the calling place.
Syntax:
return expression
#A function to return sum of two numbers
def sum(a,b):
return a+b
res=sum(5,10)
print('the result is',res)
Output:
the result is 15
Scope of Variables
The scope of a variable determines the portion of the program where you can
access a particular identifier.
1.Global variables
2.Local variables
21
Example:
return total
sum( 10, 20 )
Function Composition
# Function to add 2
# to a number
def add(x):
return x + 2
# Function to multiply
# 2 to a number
def multiply(x):
return x * 2
22
# multiply to add 2 to a number
# and then multiply by 2
print("Adding 2 to 5 and multiplying the result with 2: ",
multiply(add(5)))
Output:
Adding 2 to 5 and multiplying the result with 2: 14
23