Unit Ii (Notes-2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

FUNCTIONS IN PYTHON:

In Python, a function is a group of related statements that performs a specific task.

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

1.functions with no arguments and no return value

2.functions with no arguments with return type

3.functions with argument and no return type

4.functions with argument and return type

o Guidelines to define a function:


o The def keyword, along with the function name is used to define the function.
o The identifier rule must follow the function name.
o A function accepts the parameter (argument), and they can be optional.
o The function block is started with the colon (:), and block statements must be
at the same indentation.
o The return statement is used to return the value. A function can have only
one return

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:

There are three types of functions in Python:


• Built-in functions - The built-in functions are those functions that are pre-
defined in Python.
• Built-in functions, such as help() to ask for help, min() to get the minimum
value, print() to print an object to the terminal,… You can find an overview with
more of these functions here.
• User-define functions(UDFs) - The user-defined functions are those define by
the user to perform the specific task.

• Anonymous functions, which are also called lambda functions because they
are not declared with the standard def keyword.

Flow of Execution in Python Function


o the flow of execution refers to the order in which statements are executed
during a program run. In other words the order in which statements are
executed during a program run called flow of execution.
o Consider the code of python

x=int(input(“Enter any no=”)) # Line 1


sqr=x * x # Line 2
print(sqr) # Line 3

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.

From a function's perspective:

Parameters:

A parameter is the variable defined within the parentheses during function


definition. Simply they are written when we declare a function.

Example:

# Here a,b are the parameters

def sum(a,b):

print(a+b)

sum(1,2)

Arguments:

An argument is a value that is passed to a function when it is called. It might


be a variable, value or object passed to a function or method as input. They
are written when we are calling the function.

Example:

def sum(a,b):

print(a+b)

# Here the values 1,2 are arguments

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

4.Variable number of 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.

Consider the following example.

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

Example 2 providing the values in different order at the calling

#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:

Simple Interest: 1900.0

If we provide the different name of arguments at the time of function call, an error will
be thrown.

Consider the following example.

Example 3

#The function simple_interest(p, t, r) is called with the keyword arguments.

def simple_interest(p,t,r):

return (p*t*r)/100

# doesn't find the exact match of the name of the arguments (keywords)

print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))

6
Output:

TypeError: simple_interest() got an unexpected keyword argument 'time'

4.Variable-length Arguments (*args)

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.

However, at the function definition, we define the variable-length argument using


the *args (star) as *<variable - name >.

Consider the following example.

Example

def printme(*names):

print("type of passed argument is ",type(names))

print("printing the passed arguments...")

for name in names:

print(name)

printme("john","David","smith","nick")

Output:

type of passed argument is <class 'tuple'>

printing the passed arguments...

john

David

smith

nick

7
Python Modules

A Python module is a file containing Python definitions and statements. A


module can define functions, classes, and variables. A module can also
include runnable code. Grouping related code into a module makes the code
easier to understand and use. It also makes the code logically organized.
Example: create a simple module
# A simple module, calc.py

def add(x, y):


return (x+y)

def subtract(x, y):


return (x-y)

Import Module in Python – Import statement

We can import the functions, classes defined in a module to another module


using the import statement in some other Python source file.

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.

Example: Importing modules in Python


# importing module calc.py
import calc

print(calc.add(10, 2))

The from import Statement

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

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output:

4.0

720

Import all Names – From import * Statement


The * symbol used with the from import statement is used to import all the
names from a module to a current namespace.
Syntax:
from module_name import *
The use of * has its advantages and disadvantages. If you know exactly what
you will be needing from the module, it is not recommended to use *, else do
so.

Example: Importing all names

from math import *

Control flow statements in Python

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.

Python has three types of control structures:

• Sequential - default mode


• Selection - used for decisions and branching

9
• Repetition - used for looping, i.e., repeating a piece of code multiple times
Conditional statements or Selection/Decision control statements

In Python, the selection statements are also known as Decision


control statements or branching statements.
The selection statement allows a program to test several conditions
and execute instructions based on which condition is true.
Some Decision Control Statements are:

• Conditional (Simple if)


• Alternative(if-else)
• Nested conditionals (nested if)
• Chained Conditionals (if-elif-else)

1.Conditional (Simple if):If statements are control flow statements


that help us to run a particular code, but only when a certain condition is
met or satisfied. A simple if only has one condition to check.

n = 10

if n % 2 == 0:

print("n is an even number")

10
output:
n is an even number

2.Alternative(if-else):The if-else statement evaluates the condition


and will execute the body of if if the test condition is True, but if the
condition is False, then the body of else is executed.

n = 5

if n % 2 == 0:

print("n is even")

else:

print("n is odd")

Output
n is odd

3.Nested conditionals nested if: Nested if statements are an if


statement inside another if statement.

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

if-elif-else: The if-elif-else statement is used to conditionally


execute a statement or a block of statements.
12
x = 15

y = 12

if x == y:

print("Both are Equal")

elif x > y:

print("x is greater than y")

else:

print("x is smaller than y")

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

The syntax of a while loop in Python programming language is –

while expression:
statement(s)

• Python uses indentation as its method of grouping statements.


• Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Flow diagram:

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)

• If a sequence contains an expression list, it is evaluated first. Then, the


first item in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned to
iterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.
Flow Diagram

Example

#!/usr/bin/python

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example

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!

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the
sequence itself. Following is a simple example –

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"

When the above code is executed, it produces the following result −


Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

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.

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:

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!")

The break Statement :


With the break statement we can stop the loop even if the while
condition is true:

Example
Exit the loop when i is 3:
i = 1

17
while i < 6:
print(i) 19
if i == 3:
break
i += 1

The continue Statement :


With the continue statement we can stop the current iteration, and
continue with the next:

Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

# Note that number 3 is missing in the result

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:

for val in sequence:


pass
program:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Fruitful function and Void function

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

Void function without return statement

19
def fun1():

print("Python")

Void function with return statement


def fun2():

print("ITVoyagers")

return

Void function with parameter without return statement


def fun1(a,b):

print("sum of a and b", a+b)

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.

Fruitful function with parameter and return statement


def fun2(a,b):

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.

In interactive mode result is displayed directly on screen

>>> import math

>>> 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

All variables in a program may not be accessible at all locations in that


program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can
access a particular identifier.

There are two basic scopes of variables in Python-

1.Global variables

2.Local variables

Global vs. Local variables


• Variables that are defined inside a function body have a local
scope, and those defined outside have a global scope.
• This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables can
be accessed throughout the program body by all functions.
• When you call a function, the variables declared inside it are
brought into scope.

21
Example:

total = 0 # This is global variable.

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them.

total = arg1 + arg2; # Here total is local variable.

print ("Inside the function local total : ", total)

return total

# Now you can call sum function

sum( 10, 20 )

Function Composition

Function composition is the way of combining two or more functions in such


a way that the output of one function becomes the input of the second
function and so on. For example, let there be two functions “F” and “G” and
their composition can be represented as F(G(x)) where “x” is the argument
and output of G(x) function will become the input of F() function.
Example:

# 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

# Printing the result of


# composition of add and

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

You might also like