Python Unit3
Python Unit3
(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
DATA SCIENCE
I YEAR –B.E/B.TECH
(Common to all Branches)
PREPARED BY APPROVED BY
J.PRIYA HOD
UNIT III
FUNCTIONS AND STRINGS
Modules and functions: function definition and use, flow of execution, parameters and
arguments; Fruitful functions: return values, composition, recursion; Strings: string slices,
immutability, Looping and counting, String methods.
Modules:
Python module can be defined as a python program file which contains a python code including
python functions, class, or variables. The python code file saved with the extension (.py) is
treated as the module. a runnable code is present inside the python module. A module in
Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note:
In python help () is there. The name of any module, keyword, or topic can be entered to get
help on writing Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type
"quit".
Some of the modules like os, date, and calendar so on……
>>> import sys
>>> print(sys.version)
3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:37:30) [MSC v.1927 32 bit (Intel)]
>>> print(sys.version_info)
sys.version_info(major=3, minor=8, micro=6, releaselevel='final', serial=0)
>>>print(calendar.isleap(2020))
True
>>> print(calendar.isleap(2017))
False
Functions
➢ 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.
➢ Python enables its programmers to break up a program into segments commonly known as
functions, each of which can be written more or less independently of the others. Every function in
the program is supposed to perform a well-defined task.
Output:
Absolute value of -20 is: 20
Output:
The sum is 25
Resolution of Names
• Scope defines the visibility of a name within a block. If a local variable is defined in a
block, its scope is that particular block. If it is defined in a function, then its scope is all
blocks within that function.
• When a variable name is used in a code block, it is resolved using the nearest enclosing
scope. If no variable of that name is found, then a NameError is raised. In the code given
below, str is a global string because it has been defined before calling the function.
• Example:
Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
5. Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statement
there, and then comes back to pick up where it left off.
Example:
#example for flow of execution
print("welcome")
for x in range(3):
print(x)
print("Good morning ")
Output:
welcome
0
1
2
Good morning
Fruitful Function
❖ Fruitful function
❖ Void function
❖ Return values
❖ Parameters
❖ Local and global scope
❖ Function composition
❖ Recursion
Example:
Example:
#Example for fruitful function
def add(x,y):
sum=x+y
return sum
a=int(input("Enter a ="))
b=int(input("Enter b ="))
print("Addition of two numbers=",add(a,b))
Output:
Enter a=5
Enter b=5
Void Function
A function that perform action but don‟t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
The return statement is used to return values from the function definition to the to the
function call statement. Return takes zero, values or an expression. Default value is none.
Syntax:
return
Example :
#Example to show return statement in a function
def square(n):
returnn*n
print("The square is ",square(5))
Output:
The square is25
Write a Python function that takes two lists and returns True if they have at least one
common member.
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Output:
True
True
None
Functions with multiple return statements:
A function can have multiple return statements, one in each branch of a conditional. Since
these return statements are in an alternative conditional, only one runs. As soon as a
return statement runs, the function terminates without executing any subsequent
statements. Code that appears after a return statement, or any other place the flow of
execution can never reach, is called dead code.
Example:
#Example to show multiple return statements
def absolute(x):
if x<0:
print("This is if")
return-x
elif x>0: return
x
print("This is another elif") #dead code
else:
print("This is else") return
0
a=int(input("Enter the value"))
print(absolute(a))
Output:
First execution:
Enter the value -5
This is if
5
Second execution:
Enter the value 5
5
Third execution:
Enter the value 0
This is else
0
Actual parameters:
This parameter defined in the function call
Example:
#Example for actual and formal parameters
def cube(x):
return x*x*x
a=int(input("Enter the number="))
b=cube(a)
print("Cube of the given number=",b)
Example:
Enter the number=5
Cube of the given number= 125
Actual arguments, or simply ―arguments, are the values passed to functions to be
operated on. Formal parameters, or simply ―parameters, are the placeholder names for
the arguments passed.
#Type1 : No parameters and no return type
def Fun1() :
print("function 1")
Fun1()
Output:
function 1
Default parameter:
Python allows function parameter to have default values; if the function is called without the
argument, the argument gets its default value in function definition.
Example Output:
def student( name, age=17): Kumar 17
print (name, age)
student( “kumar”): Ajay 17
student( “ajay”):
Variable length parameter
Global Scope
❖ The scope of a variable refers to the places that you can see or access a variable.
❖ A variable with global scope can be used anywhere in the program.
❖ It can be created by defining a variable outside the function.
A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file. The variable
defined inside a function can also be made global by using the global statement.
def function_name(args):
.............
Example output
a=50
def add(): Global Variable
b=20 70
c=a+b
print(c)
def sub():
b=30
Local Variable
20
c=a-b
50
print(c)
print(a)
If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
Then when we try to run it shows an error,
Output:
local x: 10
global x: 5
Example output
def add():
b=20
c=a+b 70
print(c) Local Variable
def sub():
20
b=30
c=a-b Local Variable
print(c)
error
print(a)
error
print(b)
Function Composition:
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
#create a function compose2
>>> def compose2(f, g):
return lambda x:f(g(x))
>>> def d(x):
return x*2
>>> def e(x):
return x+1
>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
>>> a(5) # FunctionC(x)
12
Example: Output:
math.sqrt(math.log(10))
def 900
add(a,b):
c=a+b
return c
def
mul(c,d)
: e=c*d
return e
c=add(10,20
)
e=mul(c,30)
print(e)
❖ Function Composition is the ability to call one function from within another
function
❖ It is a way of combining functions such that the result of each function is passed as the
argument of the next function.
In other words the output of one function is given as the input of another function
is known as function composition.
Output:
Enter 1st number5
Enter 2nd number5
The addition of two numbers is: 10
In this example the statement , int(input("Enter 1st number"))
Uses a technique known as function composition. It combines the input and int functions
into one statement. The result of the input function is passed directly to int function
Example2:
#Example for function composition
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2-x1)**2 +((y2-y1)**2))
def area(radius):
return 3.14*radius*radius
Output:
The area of circle is: 78.5
In this example, a function is written that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle. Assume that the center point
is stored in the variables xc and yc, and the perimeter point is in xp and yp.
The first step is to find the radius of the circle, which is the distance between the two
points.
radius = distance(xc, yc, xp, yp)
The next step is to find the area of a circle with that
radius: result = area(radius)
Encapsulating these steps in a function, we get:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
Recursion
A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion
Factorial of n Output
def fact(n): enter no. to find fact:5 Fact
if(n==1): is 120
return 1 else:
return n*fact(n-1)
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Strings:
❖ Strings
❖ String slices
❖ Immutability
❖ String functions and methods
❖ String module
Strings:
❖ String is defined as sequence of characters represented in quotation marks (either
single quotes ( „ ) or double quotes ( “).
❖ An individual character in a string is accessed using a index.
❖ The index should always be an integer (positive or negative).
❖ A index starts from 0 ton-1.
❖ Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
❖ Python will get the input at run time by default as a string.
❖ Python does not supportcharacterdatatype.Astringofsize1canbetreatedas
characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations onstring:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
>>>O
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.
Slice out substrings, sub lists, sub Tuples using index.
Syntax:[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps.
For example 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character print
str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Print[0:4] –HELL The Slice[n : m] operator extracts sub string
Slicing: Print[ :3] – HEL from the strings.
a=”HELLO” Print[0: ]-HELLO A segment of a string is called a slice.
Immutability:
❖ Python strings are “immutable” as they cannot be changed after they are created.
❖ Therefore [ ] operator cannot be used on the left side of an assignment.
For example:
>>> greeting= ‘Eswari college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can’t change an
existing string. The best we can do is creating a new string that is a variation on the
original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator
❖ Once we import a module, we can reference or use to any of its functions or variables
in ourcode.
❖ There is large number of standard modules also available in python.
❖ Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants and classes
Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJK
print(string.capwords("happy LMNOPQRSTUVWXYZ!"#$%&'()*+,-
birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
Escape sequences in string
Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote (") >>>print("\"")
"
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)
ILLUSTRATIVE PROGRAMS:
1. SQUARE ROOT
#Python program to find the square root of a number using newton's method using
user defined function
n= float(input("Enter a number to find the squareroot: "))
def nsquare_root(n):
estimate = n/2
newestimate = (estimate+(n/estimate))/2
estimate = newestimate
newestimate = (estimate+(n/estimate))/2
return(newestimate)
newestimate=nsquare_root(n)
print("The square root of the number using newton method is:",newestimate)
OUTPUT:
Enter a number to find the squareroot: 2
The square root of the number using newton method is: 1.414213562373095
2. GCD
Program to find GCD/HCF of two numbers using
Recursion #Program to find the gcd/hcf using recursion
def gcd(a,b):
if(a==0): return
b
if(b==0): return
a
return gcd(b,a%b) a=int(input("Enter
first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
OUTPUT:
Enter first number:8
Enter second number:12
GCD is:
4
3. EXPONENTIATION
Program:
l=[1,2,3,4,5]
s=0
for i in l:
s=s+i
print("The sum of numbers of an array using list is",s)
Output:
The sum of numbers of an array using list is 15
Sum an array of numbers(Using arrays)
Program:
from array import *
my_array=array('i',[1,2,3,4,5])
s=0
for i in my_array:
s=s+i
print("The sum of numbers of an array is",s)
Output:
6. BINARYSEARCH
Binary Search
Given a sorted list of n elements, write a function to search a given element x in
list. Search a sorted array by repeatedly dividing the search interval into half.
Begin with an interval covering the whole array. If the value of the search key is
less than the item in the middle of the interval, narrow the interval to the lower
half. Otherwise narrow it to the upper half. Repeatedly check until the value is
found or the interval is empty. The time complexity is to O(Log n).
OUTPUT:
enter upper limit5
enter the elements20
enter the elements40
enter the elements60
enter the elements80
enter the elements100
On second execution:
enter upper limit5
enter the elements20
enter the elements40
enter the elements60
enter the elements80
enter the elements100
enter element to search120
The element is not present in the list