UNIT III
FUNCTIONS, STRINGS
Functions, parameters and arguments; Fruitful functions: return
values, local and global scope, function composition, recursive
functions. Strings: string slices, immutability, string functions and
methods, string module.
Illustrative programs: Perform Linear Search, Selection sort, Sum of
all elements in a List, Pattern Programs
FUNCTIONS:
Function is a sub program which consists of set of instructions used to
perform a specific task. A large program is divided into basic building blocks
called function.
Need For Function:
❖ When the program is too complex and large they are divided into parts. Each
part is separately coded and combined into single program. Each subprogram is
called as function.
Advantages of using Function:
❖ Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
❖ Function provides code re-usability
❖ The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) Built in function
ii) User defined function
1
i) Built in functions
❖ Built in functions are the functions that are already created and stored in
python.
❖ All the libraries in python contain pre-defined snd pre tested functions.
❖ These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
ii) User Defined Functions:
❖ User defined functions are the functions that programmers create for their
requirement and use.
2
❖ These functions can then be combined to form module which can be used in
other programs by importing them.
Advantages of user defined functions:
❖ Programmers working on large project can divide the workload by making
different functions.
❖ If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
Function definition: (Sub program)
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return expression
❖ def keyword is used to define a function.
❖ Give the function name after def keyword followed by parentheses in which
parameters are given.
The parameter list must be separated by comma.
❖ End with colon (:)
❖ Inside the function add the program statements to be executed
❖ End with or without return statement
List of variable s in function definition is called formal arguments/parameter.
3
Example:
def my_add(a,b):
c=a+b
return c
Function Calling: (Main Function)
❖ Once we have defined a function, we can call it from another function,
program or even the Python prompt.
❖ To call a function we simply type the function name with appropriate
❖ arguments.
❖ List of variables used in function call is called actual arguments/parameter.
❖ When the function is invoked , interpreter checks for the function with the
correct number of arguments and type of return value used in function call.
Syntax:
func_name() - does not pass any values
func_name(arg 1,arg2,…argn) - passes values
Example:
x=5
y=4
my_add(x,y)
Flow of Execution:
Called Function
Calling function
4
❖ The order in which statements are executed is called the flow of execution
❖ Execution always begins at the first statement of the program.
❖ Statements are executed one at a time, in order, from top to bottom.
❖ 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.
❖ Function calls are like a bypass in the flow of execution. Instead of going to
thenext statement, the flow jumps to the first line of the called function, executes
all the statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the
flow of execution. This means that you will read the def statements as you are
scanning from top to bottom, but you should skip the statements of the function
definition until you reach a point where that function is called.
RETURN STATEMENT:
❖ The return statement is used to return the values to the calling function
❖ The return statement is used to exit a function and go back to the place
from where it was called.
❖ If the return statement has no arguments, then it will not return any values.
But exits from function.
Note:
When a called function returns some result back to the calling function, it is
said to return the result.
The calling function may or may not pass parameter to the called function.
5
Syntax:
return expression
Example: Output:
def my_add(a,b): 9
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Function Prototypes: (Types of User Defined Functions)
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
i) Function without arguments and without return type
❖ In this type no argument is passed through the function call and no output is
return to calling function
❖ The sub function will read the input values perform the operation and print
the result in the same block
Syntax: Example: OUTPUT:
def add():
enter a 5
def func_name():
a=int(input("enter a"))
Statements enter b 10
b=int(input("enter b"))
15
c=a+b
func_name()
print(c)
add()
6
ii) Function with arguments and without return type
❖ Arguments are passed through the function call but output is not return to
the calling function
Syntax: Example: OUTPUT:
def func_name(arg): def add(a,b):
enter a 5
statements
c=a+b enter b 10
print(c) 15
a=int(input("enter a"))
func_name(arg)
b=int(input("enter b"))
add(a,b)
iii) Function without arguments and with return type
❖ In this type no argument is passed through the function call but output is
return to the calling function.
❖ If the function returns a value, then it has to be assigned to variable in the
calling function
variable_name=func_name(arg)
Syntax: Example: OUTPUT:
def func_name(): def add(): enter a 5
statements a=int(input("enter a")) enter b 10
return expression b=int(input("enter b")) 15
c=a+b
variable_name=func_name() return c
c=add()
print(c)
7
iv) Function with arguments and with return type
In this type arguments are passed through the function call and output is return to
the calling function
Syntax: Example: OUTPUT:
def add(a,b):
def func_name(arg): enter a 5
c=a+b
statements enter b 10
return c
return expression 15
a=int(input("enter a"))
variable_name=func_name(arg)
b=int(input("enter b"))
c=add(a,b)
print(c)
PARAMETERS AND ARGUMENTS:
The input the function takes are known as arguments/parameters.
Parameters:
❖ Parameters are the value(s) provided in the parenthesis when we write
function header.
❖ These are the values required by function to work.
❖ If there is more than one value required, all of them will be listed in
parameter list separated by comma.
❖ Example: def my_add(a,b):
Arguments :
❖ Arguments are the value(s) provided in function call/invoke statement.
❖ List of arguments should be supplied in same way as parameters are listed.
8
❖ Bounding of parameters to arguments is done 1:1, and so there should be
same number and type of arguments as mentioned in parameter list.
❖ Example: my_add(x,y)
Eg:
#function definition
def my_add(a,b): Parameters
return a+b
#function call
my_add(2.3) Arguments
PARAMETERS/ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
1. Required Arguments:
❖ The number of arguments in the function call should match exactly with the
function definition.
Example: Output:
def my_details( name, age ): Name: george
print("Name: ", name)
Age 56
print("Age ", age)
return #optional
my_details("george",56)
9
2. Keyword Arguments:
❖ Python interpreter is able to use the keywords provided to match the values
with parameters even though if they are arranged in out of order.
Example: Output:
def my_details( name, age ): Name: george
print("Name: ", name) Age 56
print("Age ", age)
return
my_details(age=56,name="george")
3. Default Arguments:
❖ 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 my_details( name, age=40 ): Name: george
print("Name: ", name)
Age 40
print("Age ", age)
return
my_details(“george")
4. Variable length Arguments
❖ Sometimes, we do not know in advance the number of arguments that will be passed
into a function.
❖ Python allows us to handle this kind of situation through function calls with number
of arguments.
❖ In the function definition we use an asterisk (*) before the parameter name to denote
this is variable length of parameter.
10
Example: Output:
def student( name,*mark): bala 102 90
print(name,mark)
student (“bala”,102,90)
Example: Output:
def arrear(name, *sub): Arun
print(name) maths
for i in sub: english
print(i)
arrear('Arun','maths','english') Anu
print() maths
arrear('Anu','maths','physics','chemistry','english') physics
chemistry
English
FRUITFUL FUNCTIONS
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25) Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
11
VOID FUNCTION
❖ A function that perform action but don’t return any value.
Example: Example:
print(“Hello”) def add():
a=10
b=20
c=a+b
print(c)
add()
RETURN VALUES:
❖ return keywords are used to return the values from the function.
❖ return a – return 1 variable
Example: Output:
def add(): enter a 6
a=int(input("enter a")) enter b 8
b=int(input("enter b")) 14
c=a+b
return c
c=add()
print(c)
❖ return a,b– return 2 variables
❖ return a,b,c– return 3 variables
12
Example: Output:
def add(): enter a 6
a=int(input("enter a")) enter b 7
b=int(input("enter b")) The value of x: 6
c=a+b The value of y: 7
return a,b,c The value of z: 13
x,y,z=add()
print("The value of x:",x)
print("The value of y:",y)
print("The value of z:",z)
❖ return a+b– return expression
Example: Output:
def add(): enter a 7
a=int(input("enter a")) enter b 8
b=int(input("enter b")) 15
return a+b
c=add()
print(c)
13
❖ return 8– return value
Example: Output:
def add(): enter a 7
a=int(input("enter a"))
enter b 8
b=int(input("enter b"))
print(c) 15
return 1
add()
LOCAL AND GLOBAL SCOPE
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.
Example:
a=50
b=20 Global Variable
def add():
b=20 Local Variable
print(a+b) 70
def sub():
Local Variable
b=30
80
print(a-b)
add()
sub()
50
print(a)
20
print(b)
14
Local Scope A variable with local scope can be used only within the function
function.
Example:
a=50 Global Variable
def add():
b=20 Local Variable
print(a+b) 70
def sub():
b=30 Local Variable
print(a-b) 80
add()
sub()
50
print(a)
print(b) Error
FUNCTION COMPOSITION:
❖ 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.
Example: Output:
Find sum and average using function
enter a:4
composition
def sum(a,b): enter b:8
sum=a+b the average is 6.0
return sum
15
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
average=avg(sum(a,b))
print("the average is",average)
Example: Output:
def add(x): 14
return x + 2
def multiply(x):
return x * 2
print(multiply(add(5)))
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
def fact(n): Output:
if(n==1): enter no. to find fact:5
return 1 Fact is 120
else:
return n*fact(n-1)
n=eval(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
16
Explanation
Examples:
Sum of n numbers
def sum(n): Output
if(n==1): enter no. to find sum:6
return 1 Sum is 21
else:
return n+sum(n-1)
n=eval(input("enter no. to find sum:"))
sum=sum(n)
print("Sum is",sum)
17
Exponential of a number using recursion
def power(base,exp):
Output
if(exp==1):
Enter base: 2
return(base)
Enter exponential value: 4
if(exp!=1):
Result: 16
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
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 to n-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 support character data type. A string of size 1 can be treated
as characters.
18
Creation of Strings:
Strings can be created by enclosing characters inside a single quote or
double-quotes. Even triple quotes can be used in Python but generally used to
represent multiline strings
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(‘’’ ‘’’) /(“”” “””)
Example:
my_string = ‘Python’
my_string = “Python”
my_string = ‘’’Python’’’
my_string = “”” This is my first
string creation in Python”””
OPERATIONS ON STRING:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
19
1. Indexing:
❖ We can access individual characters using indexing
❖ Index starts from 0 to n-1
❖ Trying to access a character out of index range will raise an IndexError.
❖ The index must be an integer.
❖ Python allows negative indexing for its sequences.
❖ The index of -1 refers to the last item, -2 to the second last item and so on.
20
Example: Output:
str = "HELLO" H
print(str[0]) E
print(str[1]) L
print(str[2]) L
print(str[3]) O
print(str[4])
2. Slicing:
❖ The process of extracting a sub string from a string is called slicing.
❖ We can access a range of items in a string by using the slicing
operator :(colon).
21
❖ We can do the negative slicing in the string.
❖ It starts from the rightmost character, which is indicated as -1. The second
rightmost index indicates -2, and so on.
22
3. Concatenation:
❖ Joining of two or more strings into a single one is called concatenation.
❖ The + operator does this in Python.
Example Output:
a = "Hello"
HelloWorld
b = "World"
c=a+b
print(c)
Example Output:
To add a space between them, add a " ":
Hello World
a = "Hello"
b = "World"
c=a+""+b
print(c)
4. Repetition:
❖ The * operator can be used to repeat the string for a given number of
times.
Example Output:
str1 = 'Hello'
str1 * 3 = HelloHelloHello
print('str1 * 3 =', str1 * 3)
23
5. Membership:
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.
Example: Output:
str = “Hello”
print('w' in str) False
print('wo' not in str1) True
print(‘o’ in str) True
print(‘llo’ in str) True
IMMUTABILITY:
❖ Python is Object oriented programming language.
❖ Any information(Number, String or Collection) stores in Object format only.
24
❖ 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.
Example:
25
❖ When we try to create multiple String objects with the same content,
duplicate objects will not be created. The address of object will be shared.
❖ In the above code, both s1 & s2 objects pointing to same location.
Does s2 effects when we modify s1 content in the above code?
❖ No, String object is Immutable. When the contents are same then only
locations are same. When we modify the content, a new object will be created
in another location.
26
STRING FUNCTIONS AND METHODS
A method is a function that “belongs to” an object.
Syntax to access the method
[Link]()
a=”happy birthday”
here, a is the string name.
27
a="Hello world"
b="-" Output:
print("a="+a) a=Hello world
print("b="+b) b=-
print("capitalize():",[Link]()) capitalize(): Hello world
28
print("upper():",[Link]()) upper(): HELLO WORLD
print("lower():",[Link]()) lower(): hello world
print("title():",[Link]()) title(): Hello World
print("swapcase():",[Link]()) swapcase(): hELLO WORLD
print("split():",[Link]()) split(): ['Hello', 'world']
print("center():",[Link](19,'*')) center(): ****Hello world****
print("replace():",[Link]("l","i")) replace(): Heiio worid
print("join():",[Link](a)) join(): H-e-l-l-o- -w-o-r-l-d
s="hello1"
print("isupper():",[Link]()) isupper(): False
print("islower():",[Link]()) islower(): True
print("isalpha():",[Link]()) isalpha(): False
print("isalnum():",[Link]()) isalnum(): True
print("isdigit():",[Link]()) isdigit(): False
print("isspace():",[Link]()) isspace(): False
print("istitle():",[Link]()) istitle(): False
print("startswith():",[Link]("h")) startswith(): True
print("endswith():",[Link]("l")) endswith(): False
print("find():",[Link]("hello")) find(): 0
print("len():",len(s)) len(): 6
print("min():",min(s)) min(): 1
print("mix():",max(s)) mix(): o
29
STRING MODULES:
❖ A module is a file containing Python definitions, functions, statements.
❖ Standard library of Python is extended as modules.
❖ To use these modules in a program, programmer needs to import the module.
❖ Once we import a module, we can reference or use to any of its functions or
variables in our code.
❖ 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
Example
import string
print([Link])
print([Link])
print([Link])
print([Link]("happ
y birthday"))
print([Link])
print([Link])
output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
30
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
Escape sequences in string
31
Illustrative programs: Perform Linear Search, Selection sort, Sum of all
elements in a List, Pattern Programs
Linear Search:
❖ Searching is a technique to find the particular element is present or not in the
given list.
❖ There are two types of searching -
Linear Search
Binary Search
❖ Linear search is a method of finding elements within a list.
❖ It is also called a sequential search.
❖ It is the simplest searching algorithm because it searches the desired element
in a sequential manner.
❖ It compares each and every element with the value that we are searching for.
If both are matched, the element is found, and the algorithm returns the key's
index position.
Concept of Linear Search
Let's understand the following steps to find the element key = 7 in the given list.
Step - 1: Start the search from the first element and Check key = 7 with each
element of list x.
32
Step - 2: If element is found, return the index position of the key.
Step - 3: If element is not found, return element is not present.
Perform Linear Search
l=[] Output:
n=int(input("No of elements")) No of elements5
for i in range(n): element1
a=int(input("element")) element2
33
[Link](a) element3
search=int(input("Element to be searched")) element4
for i in l: element5
if (i==search): Element to be searched3
print("Element found") Element found
break Sample output2
else: No of elements5
print("element not found") element1
element2
element3
element4
element5
Element to be searched7
element not found
Selection sort
❖ Selection sort is a sorting algorithm that selects the smallest element from an
unsorted list in each iteration and places that element at the beginning of the
unsorted list.
Working of Selection Sort
1. Set the first element as minimum.
34
2. Compare minimum with the second element. If the second element is smaller
than minimum, assign the second element as minimum.
Compare minimum with the third element. Again, if the third element is
smaller, then assign minimum to the third element otherwise do nothing. The
process goes on until the last element.
Compare minimum with the remaining elements
3. After each iteration, minimum is placed in the front of the unsorted list.
Swap the first with minimum
4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3
are repeated until all the elements are placed at their correct positions.
35
36
l=[] Output:
n=int(input("No of elements:")) No of elements:5
for i in range(n): element:56
a=int(input("element:")) element:67
[Link](a) element:12
print("Before Sorting:",l) element:34
for step in range(n): element:42
min_idx = step Before Sorting: [56, 67, 12, 34, 42]
for i in range(step + 1, n): After Sorting: [12, 34, 42, 56, 67]
if l[i] < l[min_idx]:
min_idx = i
(l[step], l[min_idx]) = (l[min_idx], l[step])
print("After Sorting:",l))
Sum of all elements in a List
l=[] Output:
n=int(input("No of elements:")) No of elements:5
for i in range(n): element:34
a=int(input("element:")) element:12
[Link](a) element:56
print("The elements in the list are:",l) element:23
total = 0 element:78
for ele in range(0, len(l)): The elements in the list are: [34, 12,
total = total + l[ele] 56, 23, 78]
print("Sum of all elements in given list: ", total) Sum of all elements in given list: 203
37
Program to print pattern
s=input("Enter a string:") Output:
length=len(s) Enter a string:python
for row in range(length): p
for col in range(row+1): py
print(s[col],end="") pyt
print() pyth
pytho
python
Write a python program to remove the characters which have odd index
values of a given string
def odd_values_string(x): Output:
result ="" Enter a string:python
for i in range(len(x)): pto
if i %2==0:
result = result +x[i]
return result
38
s=input("Enter a string:")
print(odd_values_string(s))
Write a Python program to check if a string has at least one letter and one
number
def checkString(x): Sample Input: thishasboth29
flag_l =False Sample Output: True
flag_n =False
for i in x: Sample Input: python
if [Link](): Sample Output: False
flag_l =True
if [Link]():
flag_n =True
return flag_l and flag_n
s=input("Enter a string:")
print(checkString(s))
39