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

Functions

The document discusses different types of functions in Python. It covers functions with no parameters and no return values, functions with parameters but no return value, and functions with parameters and a return value. It defines parameters and arguments, and how parameters work within functions. Examples are provided to illustrate functions that take in parameters but have no return value, and functions that take in parameters and return a value using the return keyword. The key points around functions and their uses are explained.

Uploaded by

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

Functions

The document discusses different types of functions in Python. It covers functions with no parameters and no return values, functions with parameters but no return value, and functions with parameters and a return value. It defines parameters and arguments, and how parameters work within functions. Examples are provided to illustrate functions that take in parameters but have no return value, and functions that take in parameters and return a value using the return keyword. The key points around functions and their uses are explained.

Uploaded by

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

Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.

com

Chapter-3: FUNCTIONS
In this tutorial we will discuss the following topics

S. No. Topics

1 Python: Functions

2 Types of Functions

3 1. Functions with no parameters and no return values.

4 2. Functions with parameters and no return value.

5 3. Functions with parameters and return value.

6 4. Functions with Multiple Return Values

7 Function Parameters and Arguments

8 Python: Types of Argument

9 1. Positional Arguments:

10 2. Default Arguments

11 3. Keyword Arguments

12 4. Variable length Positional Arguments

13 5. Variable length Keyword Arguments

14 Functions and Scopes 1. Global Scope: 2. Local scope:- 3. Nonlocal variable

15 Mutable/Immutable Properties of Data Objects

16 Passing String to Functions Passing Lists to Functions

17 Passing Tuples to Functions Passing Dictionaries to Functions

18 Functions Using Mathematical Libraries:

19 String methods & built in functions:-

Page 1 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Python: Functions

What are Functions?

 A function is like a subprogram

– A small program inside of a program

 The basic idea:

– We write a sequence of statements

– And give that sequence a name

– We can then execute this sequence at any time by referring to the


sequence’s name

Why Use Functions?

 Functions reduce code duplication and make programs more easy to


understand and maintain

 Having identical (or similar) code in more than one place has various
downsides:

– Don’t want to write the same code twice (or more)

– The code must be maintained in multiple places

– Code is harder to understand with big blocks of repeated code


everywhere

 Functions are used when you have a block of code that you want to be able to:

– Write only once and be able to use again

• Example: getting input from the user

– Call multiple times at different places


Page 2 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
• Example: printing out a menu of choices

– Differ a little bit when you call it each time

• Example: printing out a greeting to different people

 Code sharing becomes possible

Point to Remember:
 It always starts with the keyword def (for define)
 next after def goes the name of the function (the rules for naming functions
are exactly the same as for naming variables)
 after the function name, there's a place for a pair of parentheses (they
contain nothing here, but that will change soon)
 the line has to be ended with a colon;
 the line directly after def begins the function body - a couple (at least one) of
necessarily nested instructions, which will be executed every time the
function is invoked; note: the function ends where the nesting ends, so you
have to be careful.
 Function must be called/ invoked to execute.

Page 3 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
We're ready to define our first program using function.
The function is extremely simple, but fully usable. We've named it communication,
let’s create it.

def communication ():

print ("Welcome to python programming’s World. ")


print ("We start here.")

print ("We end here.")

Note: we don't use the function at all in the above program - there's no invocation
or calling of it inside the code.

When you run the above code, you see the following output:
We start here.
We end here.

This means that Python reads the function's definitions and remembers them, but
won't launch any of them without your permission.

Now we've modified the above code


We've inserted the function's invocation between the start and end messages:

Page 4 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
The output looks different now:
We start here.
Welcome to python programming’s World.
We end here.

It tries to show you the whole process:


 when you invoke a function, Python remembers the place where it happened
and jumps into the invoked function;
 the body of the function is then executed;
 reaching the end of the function forces Python to return to the place directly
after the point of invocation.
Function in python Programming Language can be creating in different form.
Lets discuses each of the form of function with the help of example:

1. Functions with no parameters and no return values.


 A python function without any arguments means you cannot pass data.
 A function which does not return any value cannot be used in an
expression it can be used only as independent statement.

 Let’s have an example to illustrate this.

Page 5 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
OUTPUT:

We start here.
Welcome to python programming’s World.
We end here.

Before discussing second form of python’s function we must know,

What is a Parameter?
 A parameter is a variable that is initialized when we call a function

 parameters exist only inside functions in which they have been defined

 Parameters are given in the parenthesis ( ) separated by comma.

 Values are passed for the parameter at the time of function calling.

How Parameters Work?

 Each function is its own little subprogram

 Variables used inside of a function are local to that function

 Even if they have the same name as variables that appear outside that
function

 The only way for a function to see a variable from another function is for that
variable to be passed in as a parameter

We can create a communication () function that takes in a person’s name (a string)


as a parameter

2. Functions with parameters and no return value.


 This type of function can accept data from calling function
 We can control the output of function by providing various values as
arguments.
Page 6 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
 Let’s have an example to get it better.

Function Parameters and Arguments


Parameter Argument
Parameters are the name within Arguments are the values passed in
the function definition. when the function is called.
Parameters don’t change when the Arguments are probably going to be
program is running different every time the function is
called.
This is also known as formal Arguments are also known as actual
parameters parameters.

Function Parameter or Formal parameter

Function Argument or Actual Parameter of


a function

Page 7 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
3. Functions with parameters and return value.
– To have a function return a value after it is called, we need to use the return
keyword
Handling Return Values
 When Python encounters return, it
 Exits the function
 Returns control back to where the function was called
 Similar to reaching the end of a function
 The value provided in the return statement is sent back to the caller as an
expression result
 The return value must be used at the calling place by –
 Either store it any variable
 Use with print()
 Use in any expression
 Let’s have an example to illustrate this.

Page 8 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Let’s follow the flow of the code:
Step 1: Call main()
Step 2: Pass control to def main()
Step 3: Enter the side of square of s (here, s=4)
Step 4: See the function call to Area ()
Step 5: Pass control from main () to Area ()
Step 6: Set the value of side in Area () to s
Step 7: Calculate side * side
Step 8: Return to main () and set ar = return statement
Step 9: Print value of ar
Sample Output:

Enter the side of square: 4


The area of square is: 16.0

Enter the side of square: 6


The area of square is: 36.0

4. Functions with Multiple Return Values


 Sometimes a function needs to return more than one value
 To do this, simply list more than one expression in the return statement
 In three ways we can do that:
– Using tuples
– Using list and
– Using dictionary
 When calling a function with multiple returns, the code must also use multiple
assignments
Page 9 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
 Assignment is based on position, just like passing in parameters is based on
position : ar, pr = Area(side, perimeter)
 Let’s have an example to illustrate this.

Function has two parameters as


program return the two values

Keyword returns two values R and P


to calling function

Calling function Area with Actual parameters

‘ar’ get the first value return i.e. area ‘pr’ get the second value return i.e.
of square perimeter of square

OUTPUT:

Enter the side of square for area: 4


Enter the side of square for perimeter: 4
The area of square is: 16.0
The perimeter of square is: 8.0

Page 10 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Python: Types of Argument
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses.
There are 5 types of Actual Arguments allowed in Python:
1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length Positional arguments
5. Variable length Keyword arguments

1. Positional Arguments:
 A positional argument is a name that is not followed by an equal sign (=) and
default value.

 When we pass the values during the function call, they are assigned to the
respective arguments according to their position.

For example, if a function is defined as

def demo(name, age):

and we are calling the function like :

demo("Ahil", "05")

then the value “Ahil” is assigned to the argument name and the value “05” is
assigned to the argument age.

Such arguments are called positional arguments.

Page 11 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Example:

1. the value 10 is assigned


to the argument x,
2. the value 5 is assigned
to the argument y and,
3. the value 15 is assigned
to the argument z.
4. Such arguments are
called positional
arguments.
5. They match up, in that
order, to the
parameters the way
the function was
defined.

OUTPUT: 6. If we call it with a


different number of
arguments, the
interpreter will show
an error message.

2. Default Arguments
1. Python allows function arguments to have default values.
2. If the function is called without the argument, the argument gets its default
value.
3. The default value is assigned by using assignment (=) operator of the
form keywordname=value.

Page 12 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Example:

1. Parameter age is a
default argument.
2. If the function is
called without the
argument, the
argument gets its
default value.
3. info (name =”Pooja”)
is called without age
value argument.
4. As we can seen in the
output the default
value is assigned i.e.
age 17

3. Keyword Arguments
 With Keyword arguments, we can use the name of the parameter irrespective
of its position.
 All the keyword arguments must match one of the arguments accepted by the
function.
 You can mix both positional and keyword arguments but keyword arguments
should follow positional arguments

Page 13 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Example:

Point to Remember

1. In case of passing
keyword argument,
order of arguments
is not important.
2. There should be
only one value for
one parameter.
3. The passed
keyword name
should match with
the actual keyword
name.
4. In case of calling
function containing
non-keyword
arguments, order is
important.
5. If we call it with a
different number of
arguments, the
interpreter will
show an error
message.

4. Variable length Positional Arguments


 It is useful when we are not certain about number of arguments that are
required in the function definition or function would receive.
 It is quite useful to write functions that take countless number of positional
arguments for certain use cases.
Page 14 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
 Python function first fills the slots given formal arguments by passed
positional actual arguments.
 Any leftover actual (positional) arguments are captured by python as a tuple,
which is available through variable which is having prefixed * in the function
definition.
Example:

Point to Remember

1. Variables arg1, arg2


need to be filled by
actual arguments
any leftover passed
arguments can be
accessed as tuple
using vartupl.

2. Since there are no


extra positional
arguments are
OUTPUT: passed in the above
function call. The
variable vartupl is a
empty tuple.

3. As you can see in the


function call, left
over arguments are
added to tuple and
can be accessed
using given variable
vartupl.

Page 15 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
5. Variable length Keyword Arguments
 Variable length keyword arguments are very much similar to variable length
positional arguments.
 It is the mechanism to accept variable length arguments in the form keyword
arguments
 It is useful if we are not certain about number of keyword arguments that
function receives.
 Python functions captures all extra keyword arguments as dictionary and
 Makes it available by name (variable) which is prefixed by ** in the function
definition.
Example:

Point to Remember

1. Variables arg1, arg2


need to be filled by
actual arguments any
leftover passed
arguments can be
accessed as
dictionary using
kwarg.
2. Since there are no
extra positional
arguments are
passed in the above
function call. The
OUTPUT:
variable kwarg is a
empty dictionary.
3. As you can see in the
function call, left
over arguments are
added to dictionary
and can be accessed
using given variable
kwarg.
Page 16 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Functions and Scopes
 A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable can’t be accessed.
 Scope determines visibility of identifiers across function/procedure boundaries
Global and local Variables in Functions
In Python 3.x there are broadly 3 kinds of Scopes:
1. Global Variable
2. Local Variable
3. Nonlocal Variable
1. Global Scope:
 A variable, with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the scope of any function/block.
 It can be accessed inside or outside of the function.
Let's see an Example 1 of how a global variable is create:
Example 1:

OUTPUT:
glb in fun : global

glb out of fun : global

– The variable gbl is defined


as global variable in above code.
– The only statement in fun() is the “print” statement.
– As there is no local glb, the value from the global glb will be used.

Page 17 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
 Changing the value of global variable ‘glb’ inside a function will not affect its
global value.

Example 2: OUTPUT

Treat as local variable inside


the fun()

glb inside fun : New glb

glb outof fun : global

No change in global variable


glb

 If you need to access and change the value of the global variable from within a
function, this permission is granted by the global keyword.

Example 3: The below given code is same as the example 2 except the use of global
keyword.

OUTPUT:

glb inside fun : New glb

glb outof fun : New glb

Page 18 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Working of above code:

 In the above program, we define glb as a global keyword inside the fun ()
function.
 Then, we assign new string to the variable glb i.e. glb = “New glb”.
 After that, we call the fun() function.
 Finally, we print the global variable glb.
 As we can see, change also occurred on the global variable outside the
function, glb= “New glb”.

2. Local scope:-
 A variable with local scope can be accessed only within the function/block
that it is created in.
 When a variable is created inside the function/block, the variable becomes
local to it.
 A local variable only exists while the function is executing.

lcl visible only inside


function fun ( )

lcl can’t be accessed


outside the fun( ) i.e.
not visible or can’t
be used outside the
fun( )

Page 19 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
3. Nonlocal variable
 Nonlocal variables are used in nested functions whose local scope is not
defined.
 The outer function’s variables will not be accessible in inner function if we do
the same, a variable will be created as local in inner function.
 In such a case, we can define the variable (which is declared in outer function)
as a nonlocal variable in inner function using nonlocal keyword.
 Let's see an example of how a keyword nonlocal is used:

OUTPUT:

The value of x is: 55

The value of y is: 10

Explanation of above code:


 As you see in the output, x and y are the variables of ofun() and
 in the infun() we declared variable x as nonlocal, thus x will not be local here
but y will be considered as local variable for infun() and

Page 20 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
 if we change the value of y that will be considered a new assigned for local
variable(for infun()) y,
 If we change the value of a nonlocal variable x (here, x= 50+x), the changes
appear in the local variable of outer function (for ofun()) also.

Mutable/Immutable Properties of Data Objects

Common immutable type:

1. Numbers: int, float, complex


2. Immutable Sequences: string, tuple

This means the value of integer, float, string, complex or tuple is not changed in the
calling block if their value is changed inside the function.

Page 21 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Common mutable type (almost everything else):

1. Mutable sequences: list


2. Set type: set
3. Mapping type: dict

Example:

Tuple x is passed to function


tuple_Immut() and function
updates the tuple

List x is passed to function


list_Mutable()function
updates the list

 We see in output that the tuple x can’t change when we pass it to tuple_Immut()
function. This is because tuple is an immutable object, so I cannot change it.
 But list x changes when we pass it to list_Mutable() function. This is because lists
are mutable.

Page 22 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Passing String to Functions

 Function can accept string as a parameter


 If you pass immutable arguments like strings to a function, the passing acts like
call-by-value so function can access the value of string but cannot alter the
string
 To modify string, the trick is to take another string and concatenate the
modified value of parameter string in the newly created string.
 Let us see few examples of passing string to function.

Example 1: Write function that will accept a string and return reverse of the
string.

Page 23 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Example 2: Write a Python function that accepts a string and calculate the number
of upper case letters and lower case letters.

Page 24 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Passing Lists to Functions

 We can also pass List to any function as parameter


 Due to the mutable nature of List, function can alter the list of values in place.
 It is mostly used in data structure like sorting, stack, queue etc.

Example 1: Write a Python function that takes a list and returns a new list with
unique elements of the first list.

Page 25 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Example 2: Write a Python function to multiply all the numbers in a list.

Passing Tuples to Functions

 Function can accept tuples as a parameter


 If you pass immutable arguments like tuple to a function, the passing acts like
call-by-value so function can access the value of tuple but cannot alter the
tuple.
 Let us see an example of passing tuples to function.

Page 26 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Example 1: Print the prime numbers from give list of numbers using tuple passing to
function.

1. Iterate through each number in a list

2. Check whether it is divisible by 2 or more numbers

3. If num is divisible by itself and 1 then it is prime and stores it in tuple.

This statement used to


concatenate tuple item i
to tuple prime

Page 27 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Passing Dictionaries to Functions

 Python also allows us to pass dictionaries to function


 Due to its mutability nature, function can alter the keys or values of dictionary
in place

Example:

OUTPUT:

Page 28 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
Functions Using Libraries: Mathematical
and String Functions
Functions Using Mathematical Libraries:
S.No. Function and its Description Example Output
prototype
1 math.ceil(x) It returns the smallest >>>math.ceil(-45.17) -45
integer not less than x, >>>math.ceil(100.12) 101
where x is a numeric
expression. >>>math.ceil(100.72) 101

2 math.sqrt(x) It returns the square root >>>math.sqrt(100) 10


of x for x > 0, where x is a >>>math.sqrt(7) 2.645751311
numeric expression.
3 math.exp(x) It returns exponential of >>>math.exp(-45.17) 2.42E-20
x: exp, where x is a >>>math.exp(100.12) 3.03E+43
numeric expression.
>>>math.exp(100.72) 5.52E+43

4 math.fabs(x) It returns the absolute >>>math.fabs(-45.17) 45.17


value of x, where x is a >>>math.fabs(100.12) 100.12
numeric value.
>>>math.fabs(100.72) 100.72

5 math.floor(x) It returns the largest >>>math.floor(-45.17) -46


integer not greater than >>>math.floor(100.12) 100
x, where x is a numeric
expression. >>>math.floor(100.72) 100
6 math.log(x,base) It returns natural logarithm >>>math.log(100.12) 4.606369467
of x, for x > 0, where x is a
>>>math.log(100.72) 4.61234439
numeric expression.
7 math.log10(x) It returns base-10 >>>math.log10(100.12) 2.000520841
logarithm of x for x > 0,
>>>math.log10(100.72) 2.003115717
where x is a numeric
expression.
8 math.pow(base,e It returns the value of >>>math.pow(100, 2) 10000
xp) base and exp, where >>>math.pow(100, -2) 0.0001
base and exp are
numeric expressions. >>>math.pow(2, 4) 16
>>>math.pow(3, 0) 1

Page 29 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
9 math.sin(arg) It returns the sine of arg, >>>math.sin(3) 0.141120008
in radians, where arg >>>math.sin(-3) -0.141120008
must be a numeric value.
>>>math.sin(0) 0

10 math.cos(arg) It returns the cosine of x >>>math.cos(3) -0.989992497


in >>>math.cos(-3) -0.989992497
>>>math.cos(0) 1
>>>math.cos(math.pi) -1

11 math.tan(arg) It returns the tangent of >>>math.tan(3) -0.142546543


x in radians, where arg >>>math.tan(-3) 0.142546543
must be a numeric value.
>>>math.tan(0) 0

12 math.degree(x) It converts angle x from >>>math.degrees(3) 171.8873385


radians to degrees, >>>math.degrees(-3) -171.8873385
where x must be a
numeric value. >>>math.degrees(0) 0

13 math.radians(x) It converts angle x from >>>math.radians(3) 0.052359878


degrees to radians, >>>math.radians(-3) -0.052359878
where x must be a
numeric value. >>>math.radians(0) 0

14 abs (x) It returns distance >>>abs(-45) 45


between x and zero, >>>abs(119L) 119
where x is a numeric
expression.
15 max( x, y, z, .... ) It returns the largest of >>>max(80, 100, 1000) 1000
its arguments: where x, y >>>max(-80, -20, -10) -10
and z are numeric
variable/ expression.
16 min( x, y, z, .... ) It returns the smallest of >>> min(80, 100, 1000) 80
its arguments; where x, >>> min(-80, -20, -10) -80
y, and z are numeric
variable/expression.
17 cmp( x, y ) It returns the sign of the >>>cmp(80, 100) -1
-1 if x < y, 0 if x == y, or 1 >>>cmp(180, 100) 1

18 divmod (x,y ) Returns both quotient >>> divmod (14,5) (2,4)

Page 30 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
and remainder by >>> divmod (2.7, 1.5) (1.0, 1.20000)
division through a tuple,
when x is divided by y;
where x & y are variable
/expression.
19 len (s) Return the length (the >>> a= [1,2,3]
number of items) of an >>>len (a) 3
object. The argument
may be a sequence >>> b= “Hello”
(string, tupleor list) or a >>> len (b) 5
mapping (dictionary).
20 round( x [, n] ) It returns float x >>>round(80.23456, 2) 80.23
rounded. >>>round(-100.000056, -100
If n is not provided then 3)
x is rounded to 0 decimal >>> round (80.23456) 80
digits.

String methods & built in functions:-


Lets Consider two Strings: str1="Save Earth" and str2='welcome'
Syntax Description Example
len ( ) Return the length of the >>> print (len(str1))
string 10
capitalize ( ) Return the exact copy of >>>print (str2.capitalize())
the string with the first Welcome
letter in upper case
isalnum() Returns True if the >>>print(str1.isalnum())
string contains only FALSE
letters and digit. It
returns False ,If the The function returns False as space
is an alphanumeric character.
string contains any
>>>print('Save1Earth'.isalnum())
special character like _ ,
@,#,* etc. TRUE
isalpha() Returns True if the >>> print('Click123'.isalpha())
string contains only FALSE
letters. Otherwise >>> print('python'.isalpha())
return False. TRUE

Page 31 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
isdigit() Returns True if the >>>print (str2.isdigit())
string contains only FALSE
numbers. Otherwise it
returns False.
lower() Returns the exact copy >>>print (str1.lower())
of the string with all the save earth
letters in lowercase.
islower() Returns True if the >>>print (str2.islower())
string is in lowercase. TRUE
isupper() Returns True if the >>>print (str2.isupper())
string is in uppercase. FALSE
upper() Returns the exact copy >>>print (str2.upper())
of the string with all
letters in uppercase. WELCOME
find(sub[,start[ The function is used to >>>str='mammals'
, end]]) search the first >>>str.find('ma')
occurrence of the 0
substring in the given
string. It returns the
index at which the On omitting the start parameters,
substring starts. It the function starts the search
returns -1 if the fromthe beginning.
substring does occur in >>>str.find('ma',2)
the string. 3
>>>str.find('ma',2,4)
-1

Displays -1 because the substring


could not be found between the
index 2 and 4-1
>>>str.find('ma',2,5)
3

lstrip() Returns the string after >>> print (str)


removing the space(s) Save Earth
on the right of the >>>str.lstrip()
string. 'Save Earth'
>>>str='Teach India Movement'
Page 32 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
>>> print (str.lstrip("T"))
each India Movement
>>> print (str.lstrip("Te"))
ach India Movement
>>> print str.lstrip("Pt")
Teach India Movement
If a string is passed as argument
to the lstrip() function, it
removes those characters from the
left of the string.
rstrip() Returns the string after >>>str='Teach India Movement'
removing the space(s) >>> print (str.rstrip())
on the right of the Teach India Movement
string.
isspace() Returns True if the >>> str=' '
string contains only >>> print (str.isspace())
white spaces and False TRUE
even if it contains one
>>> str='p'
character.
>>> str.isspace())
FALSE
istitle() Returns True if the >>> str='The Green Revolution'
string is title cased. >>> str.istitle()
TRUE
>>> str='The green revolution'
>>> str.istitle()
FALSE
replace(old, The function replaces all >>>str=‟hello‟
new) the occurrences of the >>> print (str.replace('l','%'))
old string with the new He%%o
string
>>> print (str.replace('l','%%'))
he%%%%o

join () Returns a string in >>> str1=('jan', 'feb' ,'mar')


which the string >>>str=‟&”
elements have been >>> str.join(str1)
joined by a separator.
'jan&feb&mar'

Page 33 of 34
Unit I: Computational Thinking and Programming - 2 Visit to website: learnpython4cbse.com

Chapter-3: FUNCTIONS
swapcase() Returns the string with >>> str='UPPER'
case changes >>> print (str.swapcase())
upper
>>> str='lower'
>>> print (str.swapcase())
LOWER
partition(sep) The function partitions >>> str='The Green Revolution'
the strings at the first >>> str.partition('Rev')
occurrence of ('The Green ', 'Rev', 'olution')
separator, and returns
>>> str.partition('pe')
the strings partition in
three parts i.e. before ('The Green Revolution', '', '')
the separator, the >>> str.partition('e')
separator itself, and the ('Th', 'e', ' Green Revolution')
part after the separator.
If the separator is not
found, returns the string
itself, followed by two
empty strings.
split([sep[,max The function splits the >>>str='The$earth$is$what$we$all
split]]) string into substrings $have$in$common.'
using the separator. The >>> str.split($,3)
second argument is SyntaxError: invalid syntax
optional and its default
>>> str.split('$',3)
value is zero. If an
integer value N is given ['The', 'earth',
for the second 'is','what$we$all$have$in$common.']
argument, the string is >>> str.split('$')
split in N+1 strings. ['The', 'earth', 'is', 'what', 'we',
'all','have', 'in', 'common.']
>>> str.split('e')
['Th', ' Gr', '', 'n R', 'volution']
>>> str.split('e',2)
['Th', ' Gr', 'en Revolution']

Page 34 of 34

You might also like