0% found this document useful (0 votes)
5 views

PSPP UNIT 3

This document provides an overview of functions in Python, including their definitions, types (user-defined and built-in), and the importance of using functions for code reusability and organization. It explains function syntax, calling, flow of execution, parameters, arguments, return statements, and various argument types. Additionally, it covers modules, recursion, and string operations, highlighting how to define and use functions effectively in programming.

Uploaded by

Anand Duraiswamy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

PSPP UNIT 3

This document provides an overview of functions in Python, including their definitions, types (user-defined and built-in), and the importance of using functions for code reusability and organization. It explains function syntax, calling, flow of execution, parameters, arguments, return statements, and various argument types. Additionally, it covers modules, recursion, and string operations, highlighting how to define and use functions effectively in programming.

Uploaded by

Anand Duraiswamy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT III

FUNCTIONS, STRINGS
6.Functions, Function Definition And Use, Function call, Flow Of Execution, Function Prototypes,
Parameters And Arguments, Return statement, Arguments types, Modules

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.
• Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.

Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.

50
Built in function Description

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

>>>range(2,8,1) [2, #returns range of given values


3, 4, 5, 6, 7]
>>>round(7.8) 8.0 #returns rounded integer of the given number

>>>chr(5) #returns a character (a string) from an integer


\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) 5 # returns integer from string or float

>>>pow(3,5) 243 #returns power of given number

>>>type( 5.6) #returns data type of object to which it belongs


<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name:") # reads and returns the given string
enter name : George

ii) User Defined Functions:


• User defined functions are the functions that programmers create for their requirement anduse.
• 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)


• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in which arguments are given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement

51
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]

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
Pythonprompt.
 To call a function we simply type the function name with appropriate arguments.
Example:
x=5
y=4
my_add(x,y)

Flow of Execution:

• 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 the next 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.

Function Prototypes:

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

52
i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output is return to main
function
o The sub function will read the input values perform the operation and print the result in the
same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is return to the main
function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is return to the main
function
Without Return Type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)

OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15

With return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enterb")) return c
a=int(input("enter a"))
c=a+b
b=int(input("enter b"))
return c c=add(a,b)
c=add() print(c)
print(c)

OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15

53
Parameters And Arguments:
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: defmy_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.
• 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)
RETURN STATEMENT:
• 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.
Syntax:
return[expression]

Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9

ARGUMENT TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments

Required Arguments :The number of arguments in the function call should match exactly with
the function definition.

defmy_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details("george",56)

54
Output:
Name:
georgeAge56
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.

def my_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name:
georgeAge56

DefaultArguments:
Assumes a default value if a value is not provided in the function call for that argument.
defmy_details( name, age=40 ):
print("Name: ", name)
print("Age ", age) return
my_details(name="george")

Output:
Name:
georgeAge40

Variable lengthArguments
If we want to specify more arguments than specified while defining the function, variable length
arguments are used. It is denoted by * symbol before parameter.

def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")

Output:
rajanrahulmichealärjun

7.MODULES:
 A module is a file containing Python definitions ,functions, statements and instructions.
 Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the module.

55
 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.
• Every module contains many functions.
• To access one of the function , you have to specify the name of the module and the name
of the function separated by dot .This format is called dot notation.
Syntax:
import
module_namemodule_name.function_name(variable)
Importing Builtin Module: Importing User Defined Module:
import math x=math.sqrt(25) import calx=cal.add(5,4)
print(x) print(x)

Built-in python modules are,


1.math– mathematical functions:
some of the functions in math module is,
math.ceil(x) - Return the ceiling of x, the smallest integer greater

56
than or equal to x
math. floor(x) - Return the floor of x, the largest integer less than or equal to x.
math. factorial(x)-Return x factorial.
math.gcd(x,y)-Return the greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.pi - The mathematical constant π = 3.141592
math.e – returns The mathematical constant e = 2.718281

2 .random-Generate pseudo-random numbers


random.randrange(stop) random.randrange(start, stop[,
step]) random.uniform(a, b)
-Return a random floating point number

8.ILLUSTRATIVE PROGRAMS

Output
values
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value")) Enter b value 8
c=a a=8
a=b b=5
b =c
print("a=",a,"b=",b,)

Program to find distance between Output

import math enter x17


x1=int(input("enter x1")) enter y16
y1=int(input("enter y1"))
enter x25
x2=int(input("enter x2"))
y2=int(input("enter y2")) enter y27
distance =math.sqrt((x2-x1)**2)+((y2- 2.5
print(distance)

Program to circulate n numbers Output:


a=list(input("enter the list")) enter the list '1234'

print(a) ['1', '2', '3', '4']


for i in range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']

57
4) Fruitful Function


Fruitful function

Void function

Return values

Parameters

Local and global scope

Function composition
• Recursion

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)

74
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:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS(refer 2nd unit)

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 output
a=50

def add():
Global Variable
b=20 70
c=a+b
print© Local Variable

def sub():
b=30
c=a-b 20
print©
print(a) 50

75
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20

c=a+b 70
Local Variable
print©
def sub():
b=30 20

c=a-b
Local Variable

print©
print(a) error
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.

find sum and average using function output


composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

Recursion
A function calling itself till it reaches the base value - stop point of function call. Example:
factorial of a given number using recursion

76
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)

n=eval(input("enter no. to find


fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation

Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)

n=eval(input("enter no. to find sum: "))

sum=sum(n)
print("Fact is",sum)

77
5)Explain about Strings and its operation:

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.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

>>>a=”HELLO” Positive indexing helps in accessing


indexing >>>print(a[0]) the string from the beginning

>>>H Negative subscript helps in accessing


>>>print(a[-1]) the string from the end.
>>>O

Print[0:4] – HELL The Slice[start : stop] operator extracts


Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
>>>print(a+b)
Save earth

a=”panimalar ” The * operator repeats the string on the


Repetitions: >>>print(3*a) left hand side times the value on right
78
hand side.

panimalarpanimalar
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present

>>> "a" not in s


True

String slices:

A part of a string is called string slices.
• The process of extracting a sub string from a string is called slicing.
Print[0:4] – HELL The Slice[n : m] operator extracts sub
Slicing:
Print[ :3] – HEL string 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.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a
print(a)
is not defined

79
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method

Stringname.method()

a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.

80
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 output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y 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”)

81
6) Array:

Array is a collection of similar elements. Elements in the array can be accessed by index. Index
starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype

Example
Program to find sum of Output
array elements

import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like a array.

Syntax:
arrayname.fromlist(list_name)

Example
program to convert list Output
into array

import array 35
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)

82
Methods of an array

a=[2,3,4,5]

Syntax example Description

1 array(data type, array(‘i’,[2,3,4,5]) This function is used to create


value list) an array with data type and
value list specified in its
arguments.

2 append() >>>a.append(6) This method is used to add the


[2,3,4,5,6] at the end of the array.

3 insert(index,element >>>a.insert(2,10) This method is used to add the


) [2,3,10,5,6] value at the position specified in
its argument.

4 pop(index) >>>a.pop(1) This function removes the


[2,10,5,6] element at the position
mentioned in its argument, and
returns it.

5 index(element) >>>a.index(2) This function returns the index


0 of value

6 reverse() >>>a.reverse() This function reverses the


[6,5,10,2] array.

7 count() a.count() This is used to count number of

83
7.ILLUSTRATIVE PROGRAMS:

Square root using newtons method: Output:


def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8] the sum is 35
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")

84
Binary search
output
a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("element found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")

85
Two marks:
1. What is a Boolean value?

Boolean data type have two values. They are 0 and 1.

0 represents False

1 represents True

True and False are keyword.

Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0

2. Difference between break and continue.

break continue

It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.

syntax: syntax:
break continue

for i in "welcome": for i in "welcome":


if(i=="c"): if(i=="c"):
break continue
print(i) print(i)

w w
e e
l l
o
m
e

86
3. Write a Python program to accept two numbers, multiply them and print the result.

number1 = int(input("Enter first number: "))


number2 = int(input("Enter second number: "))
mul = number1 * number2
print("Multiplication of given two numbers is: ", mul)

4. Write a Python program to accept two numbers, find the greatest and print the result.
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
if(number1>number2):
print('number1 is greater',number1)
else:
print('number2 is greater',number2)

5. Define recursive function.


Recursion is a way of programming or coding a problem, in which a function calls itself one
or more times in its body. Usually, it is returning the return value of this function call. If a function
definition fulfils the condition of recursion, we call this function a recursive function.

Example:

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

6. Write a program to find sum of n numbers:

n=eval(input("enter n")) enter n


i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

7. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.

It is used when a statement is required syntactically but you don’t want any code to execute.

It is a null statement, nothing happens when it is executed.

87
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e

8. Compare string and string slices.


A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg: >>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

9. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we define a
variable on the top of the script or module, the variable is called global variable. The variables that are
defined inside a class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)

10. Mention a few string functions.


s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string

88

You might also like