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

python Function and string

This document covers the concepts of functions and strings in Python programming. It explains the definition, types, and usage of functions, including built-in, user-defined, and recursive functions, as well as various argument types. Additionally, it discusses string operations, formatting, and methods, emphasizing the immutability of strings.

Uploaded by

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

python Function and string

This document covers the concepts of functions and strings in Python programming. It explains the definition, types, and usage of functions, including built-in, user-defined, and recursive functions, as well as various argument types. Additionally, it discusses string operations, formatting, and methods, emphasizing the immutability of strings.

Uploaded by

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

Unit -II

b
Functions and Strings

Presented by Sri D Kishore babu, M.Tech, MISTE.,

4/16/2025 DEPARTMENT OFandMECHANICAL


Functions Strings ENGINEERING
Contents
Functions
Definition of Strings
Function

Basic String
Types of operations
Arguments

String formatting
Calling operators
Function

Recursive Built-in
Functions & functions
Modules
Return
Statement

FUNCTIONS AND STRINGS 4/16/2025


Function

Dividing a large program into some small independent units or blocks known as functions.

Reduce duplication Induce reusability


of code of code

By using functions, we can We can call python functions any


avoid rewriting same logic/code number of times from any part of
again and again, Thus function the program. So function induces
reduces program size. reusability in a program.

FUNCTIONS AND STRINGS 4/16/2025


Types of Function

These are predefined functions abs(), max(), min(),


The functions available in
Built-in len(),print(),input(),
1 and are always available in math module are: ceil(),
functions range(),chr(),float(),int(),
python library. floor(), fabs(), exp(),
long(),str(),type(
log(), pow(), sqrt() ),id(
cos(), )
etc.
sin()etc.
Functions These are also predefined
2
defined with functions available in different Ex: In python shell:
modules Ex: In
max( x, python shell: the
y, z) #returns
modules.
sqrt() returns
largest of its 3the square
arguments.
root of a number
>>>max(80, -70, 100)
>>>import math
100
User defined
3 These are defined by programmer. >>>math.sqrt(49)
functions
7.0

FUNCTIONS AND STRINGS 4/16/2025


User defined function

Syntax of function In Python, programmers can

def function_name(parameters) : Function Header also develop their own


function(s). They are known
statement1 as user defined functions.
Statement2
Statement3 Function Body
…………
…………
Statement N

FUNCTIONS AND STRINGS 4/16/2025


Example:
With out using function

#program for finding sum of given range number 1 to


25, 50 to 75 and 90 to 100:
s=0 Using function
for i in range(1,26):
s=s+i def sum(x,y):
print('The sum of integers from 1 to 25 is:',s) s=0
s=0 for i in range(x,y+1):
for i in range(50,76): s=s+i
s=s+i print('The sum of integers from', x,
print('The sum of integers from 50 to 76 is:',s) 'to', y, 'is:',s)
s=0
for i in range(90,101):
s=s+i
print('The sum of integers from 90 to 100 is:',s)

FUNCTIONS AND STRINGS 4/16/2025


Calling functions

def eventest(x): #function header


if x%2==0:
print("even")
else:
print("odd")
n=int(input("Enter any number:"))
#calling function
eventest(n)

When a function is called, the interpreter jumps to that function definition and executes
the statements in its body. Then, when the end of the body is reached, the interpreter
jumps back to the part of the program that called the function, and the program resumes
execution at that point. When this happens, we say that the function returns

FUNCTIONS AND STRINGS 4/16/2025


Types of arguments:
Types of arguments

Required Keyword Default Required


arguments arguments arguments arguments

Required arguments

The arguments are passed to a function in correct positional order. Also, the number of
arguments in the function call should exactly match with the number of arguments specified
in the function definition.

Otherwise
TypeError
is returned

FUNCTIONS AND STRINGS 4/16/2025


No arguments Takes 1 arguments Arguments matched

def display(): def display(str): def display(str):


print(‘Hello’) print(str) print(str)
display(‘Hi’) display() Str=‘Hello’
Display(str)
Output: Output:
TyeError: display()takes no TyeError:display()takes Output:
arguments (1 given) exactly 1 arguments (0 given) Hello
`

FUNCTIONS AND STRINGS 4/16/2025


Keyword arguments:

When calling a function with some


Keyword arguments when used in function calls, helps
values, values are assigned to the
the function to identify the arguments by the
arguments based on their position.
parameter name.

def display(str,int_x,float_y):
print(‘The string is: ‘,str)
print(‘The integer value is: ‘,int_x)
Example:
print(‘The floating point value is:’,float_y)
display(float_y=56.04,str=‘Hello’,int_x=123)
Output:
The string is: Hello
The integer value is: 123
The floating point value is: 56.04
`
FUNCTIONS AND STRINGS 4/16/2025
Default Arguments:
Python allows, default values to specify function arguments.

def display(name, course=‘B.Tech’):


print(‘Name: ‘ +name)
print(‘course:‘,course)
The default value to an arguments is provided
print(‘The floating point value is:’,float_y)
by using assignment operator (=).For example,
display(course=‘BCA’,name=‘Ravi’) # keyword arguments
if the function accepts three parameters, but
display(name=‘Chandu’)# default arguments for course
function call provides only two arguments,
Output:
then third parameter will be assigned the
Name: Ravi
default value(already specified)
Course: BCA
Name: Chandu
Course: B.Tech

FUNCTIONS AND STRINGS 4/16/2025


Variable-length Arguments:

If you do not know how many arguments that will be passed into your
function, add an asterisk (*) before the parameter name in the function
definition.

1. This variable name holds the values of all non keyword


variable arguments. Syntax:
2. The function will receive a tuple of arguments, and can Def fname([arg1,arg2,..] *var_args_tuple):
access the items accordingly. This tuple remains empty function statements
if no additional arguments are specified during the return[expression]
function call.

FUNCTIONS AND STRINGS 4/16/2025


Variable-length Arguments:

def my_function(*kids):

print("The youngest child is " + kids[2])

my_function("Ajay", "Vijay", "Sanjay")

Output:
The youngest child is Sanjay

FUNCTIONS AND STRINGS 4/16/2025


Ex: Programs:

1. Write a program to calculate the simple interest.

def interest(p,y,s):
if (s==y):
Output:
SI=float(p*y*12/100)
Enter the principle amount: 100000
return SI
Enter the number of years : 3
p=float(input(“Enter the principle amount:”))
Interest: 30000.0
y=float(input(“Enter the number of years:”))
print(“Interest:”,interest(p,y,s))

FUNCTIONS AND STRINGS 4/16/2025


Ex: Programs:

2. Write a program to calculate the volume of a cuboid using default arguments.

Output:

def volume(l,w=3,h=4): Length: 4 width: 6 Height: 2

print(“Length:”,l,”\twidth:”,w,:\tHeight:”,h) volume: 48

print(‘volume:’,volume(4,6,2)) Length: 4 width: 6 Height: 4

print(‘volume:’,volume(4,6)) volume: 96

print(‘volume:’,volume(4)) Length: 4 width: 3 Height: 4


volume: 48

FUNCTIONS AND STRINGS 4/16/2025


Lambda function The Function without Name

The Python lambda function is anonymous as it is a function without a def keyword and name.

To create a Python lambda function, we have to use the lambda keyword.

Python lambda function doesn’t have any return statement. It has only a single expression which

is always returned by default.

The syntax of lambda functions contains only a single statement.

Identifier= lambda [arg1 [,arg2,.....argn]]: expression

arguments Expression
Identifier lambda keyword

sum = lambda arg1, arg2: arg1 + arg2; # function definition header


print ("Value of total : ", sum(10, 20))
Function calling

FUNCTIONS AND STRINGS 4/16/2025


The return statement:

The Python return statement is used to return a value from a function.

Syntax:
def funtion_name():
statements
 The user can only use the return
statement in a function. It cannot be return [expression]
used outside of the Python function.
 A return statement includes the return
keyword and the value that will be
returned after that.
def adding(x, y):
i = x + y
return i
result = adding(16, 25)
print(f'Output of adding(16, 25) is {result}')

FUNCTIONS AND STRINGS 4/16/2025


Recursive Functions:

A recursive function is defined as a function that calls itself to solve a


smaller version of its task until a final call is made which does not require a
call to itself.

 Every recursive solution has two major cases.

Simple enough to be solved directly


base case without making any further calls to the
same function.

recursive solution
1 Problem divide into simpler sub-parts

recursive case 2 The function call itself with simpler


sub-parts.

3 Obtained result is combined

FUNCTIONS AND STRINGS 4/16/2025


Example:

# Write a program to calculate the factorial of a number recursively.

def fact(n):
if(n==1 or n==0):
return 1
else:
return n*fact(n-1)
n= int(input('Enter the value of n:'))
print('The factorial of ',n,'is',fact(n))

Output:
Enter the value of n: 5
The factorial of 5 is 120

FUNCTIONS AND STRINGS 4/16/2025


Example:

# Write a program to calculate GCD using recursive function.

def gcd(x,y):
rem =x%y
if(rem==0): Output:
return y Enter the first number:50
else: Enter the second number:5
return gcd(y,rem) The GCD of given numbers is 5
n=int(input('Enter the first number:'))
m=int(input('Enter the second number:'))
print('The GCD of given numbers is',gcd(n,m))

FUNCTIONS AND STRINGS 4/16/2025


Strings

FUNCTIONS AND STRINGS 4/16/2025


Strings:

String data type is a


sequence made up of one or
more individuals It is delimited by single
characters (‘’)quotes , double (“”)
quotes or even triple quotes
(“”” “””)
Strings
Declare and define a string
by creating a variable of
string type.
Python has a inbuilt string
class named ‘str’

FUNCTIONS AND STRINGS 4/16/2025


Strings

String
String Variable The index of first character
is 0
Example:
Name = “Ravi” The index of last character
is n-1
Country = “India”
Nationality = str(“Indian”)
Where,
n = number of characters
★ Index
Individual characters in a string are accessed
using the subscript([]) operator

The index specifies a position member


index of an order set.

FUNCTIONS AND STRINGS 4/16/2025


Strings ★ Traversing a string

A string can be traversed by accessing characters(s) from one index to another

For example: Message = ‘Hello’


Index = 0
for I in message:
print(Message[‘,index,’] = ‘, i)
index += 1

Output:
Message[0] = H
Message[1] = e
Message[2] = l
Message[3] = l
Message[4] = o

 If try to access 6th character, then it shows Index Error.

FUNCTIONS AND STRINGS 4/16/2025


Strings:

Concatenating string (+) Append string ( += )


The word concatenate means to join together Append means to add something at the
end.
Str1 = ‘Hello’ Str = ‘Hello’
Str2 = ‘world’ name = input(‘Enter your name’)
Str = str1+str2 Str += ‘name’
Print(‘The concatenated string is:’, str3) Str += ‘. Welcome to python programming’
Print(‘str’)
Output:
The concatenated string is: Hello World Output:
Enter your name: Ravi
Hello Ravi. Welcome to python programming

FUNCTIONS AND STRINGS 4/16/2025


Strings:

Repeat a string operator( * )

Str = ‘Hello’
Print(str*3)

Output:
HelloHelloHello

Strings: Strings are IMMUTABLE

FUNCTIONS AND STRINGS 4/16/2025


Strings:

id ()string:
Every object in python is stored in memory. You can find the object
by using id(). The id() returns the memory address of that object

Str1 = ‘Hello’
print(str1)
print(‘id of str1 is:’,id(str1))
Str2 = ‘world’
print(str2)
Print(‘id of str2 is:’,id(str2))
Output:
Hello
Id of str1 is: 45093344
World
Id of str2 is: 45093346

FUNCTIONS AND STRINGS 4/16/2025


Strings:

String formatting operator:


The format operator, % allows users to construct strings, replacing
parts of the strings with the data stored in variables.

The Syntax: ‘ <format> ‘ % (<values>)

name = ‘Ravi’ %d integer 21


Age = 21
print(‘Name = %s and Age = %d’ %(name,age))
%f float 2.30
Output:
Name = Ravi and Age = 21 %s string Ravi

%c character K

FUNCTIONS AND STRINGS 4/16/2025


Strings:

Slicing string:
A substring of a string is called a slice. [ sub-parts of sequence]
End: is last
character i.e n-1
The syntax: S[start : end]

Start specifies
the beginning of
index

P Y T H O N
Index
start 0 1 2 3 4 5
Index
-6 -5 -4 -3 -2 -1
end

FUNCTIONS AND STRINGS 4/16/2025


Strings:

Strings In-Build function


methods

FUNCTIONS AND STRINGS 4/16/2025


Thank you…!

FUNCTIONS AND STRINGS 4/16/2025

You might also like