0% found this document useful (0 votes)
63 views10 pages

Unit 3

This document provides an overview of functions and strings in Python, detailing their definitions, types, advantages, and examples. It covers built-in functions, user-defined functions, recursion, lambda functions, and string operations, including indexing, slicing, and built-in string methods. Additionally, it explains concepts like variable scope, function arguments, and the immutability of strings.

Uploaded by

senoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views10 pages

Unit 3

This document provides an overview of functions and strings in Python, detailing their definitions, types, advantages, and examples. It covers built-in functions, user-defined functions, recursion, lambda functions, and string operations, including indexing, slicing, and built-in string methods. Additionally, it explains concepts like variable scope, function arguments, and the immutability of strings.

Uploaded by

senoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1

UNIT-3 FUNCTIONS, STRINGS


What is Functions?
Functions is a group of related statements that perform a specific task.
What are the Advantages of functions?
1. It avoids repetition and enable code reusing.
2. It provides better modularity for your application
3. Better readability
4. Easy to debug

What are the types of functions?


Functions are classified in four types
1. Built-in functions : inbuilt within Python
2. User defined functions: defined by the users
3. Recursion function: Functions that calls itself
4. Lambda function: anonymous un-named function
List some of the Built-in functions in python
abs ( ) Returns an absolute value
ord ( ) Returns the ASCII value for the given Unicode character
chr ( ) Returns the Unicode character for the given ASCII value
bin ( ) Returns a binary string prefixed with “0b” for the given integer
type ( ) Returns the type of object
id ( ) Return the address of the object in memory
min ( ) Returns the minimum value in a list
max ( ) Returns the maximum value in a list
sum ( ) Returns the sum of values in a list.
help() Return information regarding the function. Eg help(print)

What is the output for the following builtin functions?


abs(-5.5) 5.5
int(5.5) 5
int(‘5’) 5
int(‘python’) ValueError
ord(‘g’) 103
chr(103) ‘g’
bin(25) '0b11001'
type(5.24) <class ‘float’>

min([10,4,7,3,9]) 3
max([10,4,7,3,9]) 10
sum([10,4,7,3,9]) 33

import math
math.sqrt()

import calendar
print(calendar.month(2024,12))

Dr. Senoj Joseph, HOD BME & EEE, ECET


2

How to define a function?


def function_name(parameters): #function header
Statement #function body

Function definition have a function header and function body.


Function header begin with the keyword “def ” followed by function name and
parenthesis ()
If any input parameters are present should be placed within these parentheses
Function header end with a colon (:).
The function body should be indented relative to function header
The statement “return [expression]” exits a function, optionally passing back an
expression to the caller. Else return “None”

Give examples of user defined functions


def hello():
print(“Hello”)
This function print hello. Does not return a value.
hello() Hello
print(hello()) None (implicit return)

def area(length, breadth):


a=length*breadth
return(a)

What is meant by function call?


A function call is a statement that runs a function. It is done by typing function name
followed by an argument list in parenthesis
eg
s=area(5,6)
print(area(2,3)) 6
Compare parameters with arguments?
Parameters are the variables used in the function definition whereas arguments are the values
we pass to the function parameters. In the function defined below length and breadth are
parameters, while values 4,5 used while calling the function is called arguments.

def area(length, breadth):


a=length*breadth
return(a)
print(area(4,5))

What are the types of function arguments?


1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments.

Dr. Senoj Joseph, HOD BME & EEE, ECET


3

What is meant by required arguments?


“Required Arguments” are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function definition.
You need atleast one parameter to prevent syntax errors to get the required output.
Eg area(5, 6) here 5 will be length and 6 will be breadth.
What is meant by keyword arguments?
The value of the keyword argument is matched with the parameter name and so, one can also
put arguments in improper order
Eg area(breadth=6, length=5)
What is meant by default arguments?
In Python the default argument is an argument that takes a default value if no value is provided
in the function call.
def area(length=2, breadth=4):
a=length*breadth
return(a)
print(area(4,5))
print(area())

>>>20
>>>8 (used default value since arguments not supplied)
What is meant by variable length arguments?
Sometimes you might need to pass more arguments than have already been specified. Variable-
Length arguments can be defined using asterisk (*).
def sum(x,y,z):
print("sum of three nos :", x+y+z)
sum(5,10,15,20,25)
>>> TypeError: sum() takes 3 positional arguments but 5 were given

SYNTAX is as follows : def function_name(*args):


def sum(*args):
s=0
for i in args:
s+=i
return(s)
print(sum(1,2,4,5,6))
>>> 18
sum(1,2,3)
>>>6

Dr. Senoj Joseph, HOD BME & EEE, ECET


4

What is anonymous function or lambda functions?


In Python, anonymous function is a function that is defined without a name. anonymous
functions are defined using the lambda keyword instead of def keyword. Lambda function can
take any number of arguments and must return one value in the form of an expression. These
functions are mainly used in combination with the functions like filter(), map() and reduce().

sum = lambda arg1, arg2: arg1 + arg2


print(sum(30,40))
>>>70

What is a return statement?


The return statement causes your function to exit and returns a value to its caller. Any number
of 'return' statements are allowed in a function definition but only one of them is executed at
run time.
This return statement can contain expression which gets evaluated and the value is returned. If
there is no expression in the statement (explicit return) or the return statement itself is not
present (implicit return) inside a function, then the function will return the None object.

What is meant by fruitful function?


A function that return a value is called fruitful function

What is meant by function composition?


Value returned by a function can be used as argument for another function in a nested manner.
This is called function composition.
a=fn2(x)
b=fn1(a)
These can be composed into a single line as shown below
b=fn1(fn2(x))

eg
a=input() # a will be a string
b=int(a) # string converted to integer
These lines can be composed into single line as below
b=int(input())

What is a recursive function?


A function that call itself is called recursive function. Useful if the problem can be expressed
in terms of similar problem of smaller size. eg
N!=N(N-1)!

Write a factorial program using recursion and explain the working


def fact(x):
If x==1:
return 1 # base class is fact(1)
else:

Dr. Senoj Joseph, HOD BME & EEE, ECET


5

return x*fact(x-1)
n=int(input(“ enter a number ”)
print(fact(n))
>>> enter a number 5
>>> 120

Suppose n=4
fact(4) 1st call
4*fact(3) 2nd call
4*3*fact(2) 3rd call
4*3*2*fact(1) 4th call
4*3*2*1 return from 4th call
4*3*2 return from 3rd call
4*6
24

Write a GCD program using recursion


GCD program (greatest common diviser)

def gcd(x,y): #assume x>y if not please swap them


if (x%y==0):
return y
else:
return gcd(y, x%y)
eg
gcd(62,8)
gcd(8,6)
gcd(6,2)
return 2
return 2
return 2

Write a Fibonacci series program using recursion


Fibonocci series 1 1 2 3 5 8 13 ….

def fibo(n):
If n<=2:
return 1
return fibo(n-1)+fibo(n-2) # we have two base class fibo(1) and fibo(2)

fibo(4)
fibo(3)+fibo(2)
fibo(2)+fibo(1)+fibo(2)

Dr. Senoj Joseph, HOD BME & EEE, ECET


6

What is meant by Infinite recursion?


If a recursion does not reach base class, it goes on making recursive call forever. In most tools
it will stop when maximum recursion depth is reached and error message will be displayed.

def recurse()
recurse()

What is meant by Scope of Variables?


Scope of variable refers to the part of the program, where it is accessible. Variable can have
two types of scopes - local scope and global scope

What is meant by Local scope?


A variable declared inside the function's body is known as local variable. A variable with local
scope can be accessed only within the function that it is created in. A local variable only exists
while the function is executing.

def loc():
y = "local"
print(y)
loc()
print(y)

>>>local
>>> NameError: name 'y' is not defined

What is meant by Global Scope?


A variable, with global scope can be used anywhere in the program. The rules are as follows
When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
We use global keyword to modify the value of the global variable inside a function.

c = 1 # global variable
def add():
print(c)
add()
>>> 1

c = 1 # global variable
def add():
c = c + 2 # Modify a global variable make it local
print(c)
add()
>>> UnboundLocal Error: local variable 'c' referenced before assignment

Without using the global keyword we cannot modify the global variable inside the function
but we can only access the global variable.

Dr. Senoj Joseph, HOD BME & EEE, ECET


7

x = 0 # global variable
def add():
global x
x=x+5
print ("Inside", x)
add()
print ("Outside", x)
>>>Inside 5
>>>Outside 5

x=5
def loc():
x = 10
print ("local x:", x)
loc()
print ("global x:", x)
Output:
local x: 10
global x: 5
STRINGS

Define Strings
In python string is a sequence of characters, numbers and special characters enclosed in single
or double quotes. Multilines string can be enclosed using triple quotes
S1=’python’
S2=”python”
S3=’”””python
Is
Fun”””

What is meant by string indexing?


An individual character is accessed using an integer subscript. Can be accessed using positive
or negative subscripts. Positive subscript start from beginning as index 0. Negative subscript
start from end backwards starting with index -1. Square bracket is used for indexing.

F=”computer”
F[0] c
F[2] m
F[7] r
F[len(F)-1] r
F[-1] r
F[-3] t
F[8] IndexError

How to traverse a string


Traversing a string means accessing all the elements of string one after another using a for or
while loop

Dr. Senoj Joseph, HOD BME & EEE, ECET


8

word=”Computer”
for i in word:
print(i, end=” “) # please note the usage of end=” “ in print command

Computer

i=0
while i<len(word):
print(word[i], end= “ “)
i+=1

Computer

What is meant by string slicing?


Slicing is used to select a portion of a string. Slicing operator [m: n] return a part of string
starting from mth character to (n-1)th character.

word=” Computer”
word[0:5] “Comp”
word[:3] “Com”
word[4:] “uter”
word[3:6] “put”
word[:] “Computer”

Why string are called immutable?


We cannot change an existing string. But a new string can be created from the variation on the
original string.

word=”Computer”
word[0]=’c’ TypeError

word=’c’+word[1:] “computer” #new variable created in same name.

Explain some of the builtin string functions.

upper() : take a string and return a new string with all upper characters

word=”Computer”
x=word.upper()
print(x) “COMPUTER”

lower() : take a string and return a new string with all lower characters

word=”COMPUTER”
print(word.lower()) “computer”

capitalize() : capitalize first character of the string

word=”computer”
print(word.capitalize()) “Computer”

Dr. Senoj Joseph, HOD BME & EEE, ECET


9

split() is used to return a list of words in a string. Default split at whitespace

s=”hello world”
print(s.split()) [‘hello’,’world’]

find() is used find first occurrence of a substring in a string else return -1

s=”hello world”
print(s.find(“wo”) 6
print(s.find(“ma”) -1
print(s.find(“wo”,0,5) -1 #checking only from 0 to 5. Hence not found

What are the other builtin string commands?


capwords() x=“hello world”.capwords() “Hello World”
count() x=“hello”.count(‘e’) 1
index() x=”hello”.index(‘o’) 4
rfind() x=”hello”.rfind(‘l’) 3 #if not found return -1
rindex() x=”hello”.rfind(‘k’) Error #if not found return ValueError
join() ‘-‘.join([‘03’,’12’,’2024’]) “03-12-2024”
strip() remove leading and trailing white space
“ hello “.strip() “hello”
replace() “hello”.replace(‘l’,’m’) “hemmo”

What is the usage of “in” operator in a string?


x=”hello”
print ( “el” in x) True
print(“He” in x) False

Give some operations using strings

Concatenation: join strings using ‘+’ operator


a=”hello”
b=”world”
print(a+b) ‘ helloworld’

Repetition: Repeat the string using * operator


a=”hello”
print(a*3) “hellohellohello” # repeat 3 times

length
a=”hello”
print(len(a)) 5 # find the length of string

Comparison: in alphabetical order


'frog'>'egg' True
'frog'> 'frock' True
'frog'>'frogs' False

Dr. Senoj Joseph, HOD BME & EEE, ECET


10

Write short note on string modules?


Contain some additional methods but we need to import the module.

import string
string.digits “0123456789”
string.ascii_letters “abc…xyzABC…XYZ”
string.ascii_lowercase “abcd….xyz”
string.ascii_uppercase “ABC….XYZ”
string.hexdigits “0123456789abcdefABCDEF”
string.octdigits “01234567”
string.punctation
string.printable
string.whitespace

Dr. Senoj Joseph, HOD BME & EEE, ECET

You might also like