0% found this document useful (0 votes)
2 views28 pages

Unit - II Python Notes

The document provides an overview of functions and modules in Python, explaining built-in and user-defined functions, as well as commonly used modules like math, random, and statistics. It covers function definition, calling, and the use of return statements, along with examples demonstrating various concepts such as scopes of variables and default parameters. Additionally, it includes practical coding examples to illustrate the application of these concepts.

Uploaded by

Gopi Krishna
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)
2 views28 pages

Unit - II Python Notes

The document provides an overview of functions and modules in Python, explaining built-in and user-defined functions, as well as commonly used modules like math, random, and statistics. It covers function definition, calling, and the use of return statements, along with examples demonstrating various concepts such as scopes of variables and default parameters. Additionally, it includes practical coding examples to illustrate the application of these concepts.

Uploaded by

Gopi Krishna
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/ 28

www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.

in

Unit – II
2.1 Functions
A function is a block of statements under a name that can execute
independently. The functions are used to perform a specific task. Functions allow us to
divide a larger problem into smaller subparts to solve efficiently, to implement the code
reusability concept and makes the code easier to read and understand.
The Python provides several functions and methods to write code very easily, and these
functions and methods are called built-in function and methods. Python allows us to create
our functions and methods, and these are called user-defined functions and methods.
2. 1.1 Built-In Functions
The Python interpreter has a number of functions that are built into it and are always
available

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.2 Commonly Used Modules


• Python standard library also consists of a number of modules. While a function is a
grouping of instructions, a module is a grouping of functions.
• A module is created as a python (.py) file containing a collection of function
definitions.
• To use a module, we need to import the module. Once we import a module, we
can directly use all the functions of that module.

The syntax of import statement is as follows:

import modulename1 [,modulename2, …]

This gives us access to all the functions in the module(s). To call a function of a
module, the function name should be preceded with the name of the module with
a dot(.) as a separator.
The syntax is as shown below:
modulename.functionname()

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.3.1 Built-in Modules


Python library has many built-in modules that are really handy to programmers. Some
commonly used modules and the frequently used functions that are found in those
modules:
• math
• random
• statistics
2.3.1.1 math module:
It contains different types of mathematical functions. In order to
use the math module we need to import it using the following statement:
import math

Commonly used functions in math module


Function Syntax Returns Example Output
>>> math.ceil(-9.7)
-9
>>> math.ceil (9.7)
math.ceil(x) ceiling value of x
10
>>> math.ceil(9)
9
>>> math.floor(-4.5)
-5
>>> math.floor(4.5)
math.floor(x) floor value of x
4
>>> math.floor(4)
4
>>> math.fabs(6.7)
6.7
>>> math.fabs(-6.7)
math.fabs(x) absolute value of x
6.7
>>> math.fabs(-4)
4.0
>>> math.factorial(5)
math.factorial(x) factorial of x
120
>>>math.fmod(4,4.9)
4.0
>>>math.fmod(4.9,4.9)
0.0
math.fmod(x,y) x % y with sign of x
>>>math.fmod(-4.9,2.5)
-2.4
>>>math.fmod(4.9,-4.9)
0.0
gcd (greatest common >>> math.gcd(10,2)
math.gcd(x,y)
divisor) of x and y 2
>>> math.pow(3,2)
𝑥𝑦
math.pow(x,y) 9.0
(x raised to the power y) >>>math.pow(4,2.5)
3

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

32.0
>>>math.pow(6.5,2)
42.25
>>>math.pow(5.5,3.2)
233.97
>>> math.sqrt(144)
12.0
math.sqrt(x) square root of x
>>> math.sqrt(.64)
0.8
>>> math.sin(0)
0
math.sin(x) sine of x in radians
>>> math.sin(6)
-0.279

2.3.1.2 random module:


This module contains functions that are used for generating random numbers. In order
to use the random module we need to import it using the following statement:
import random

Commonly used functions in random module


Function Syntax Returns Example Output
Random Real
>>> random.random()
random.random() Number (float) in
0.65333522
the range 0.0 to 1.0
x, y are integers >>>random.randint(3,7)
4
such that x <= y and
>>> random.randint(-3,5)
random.randint(x,y) returns Random
1
integer between x
>>> random.randint(-5,-3)
and y -5.0
Random integer >>> random.randrange(5)
random.randrange(y)
between 0 and y 4
>>> random.randrange(2,7)
random. Random integer
2
randrange(x,y) between x and y

2.3.1.3 statistics module:


This module provides functions for calculating statistics of numeric (Real-valued) data. In
order to use the statistics module we need to import it using the following
statement:
import statistics

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Commonly used functions in statistics module


Function Syntax Returns Example Output
>>> statistics.
mean([11,24,32,45,51])
statistics.mean(x) arithmetic mean
32.6
>>>statistics.
median (middle median([11,24,32,45,51])
statistics.median(x)
value) of x
32
>>> statistics.
mode([11,24,11,45,11])

11
mode (the most
statistics.mode(x)
repeated value) >>> statistics.
mode(("red","blue","red"))

'red'

• In order to get a list of modules available in Python, we can use the following
statement:
>>> help("module")
• To view the content of a module say math, type the following:
>>> help("math")
2.4 From Statement
Instead of loading all the functions into memory by importing a module, from statement
can be used to access only the required functions from a module. It loads only the specified
function(s) instead of all the functions in a module.
Syntax :
>>> from modulename import functionname

Example :

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.5 Function Definition and Calling the Function / User-defined Functions

Defining a function in Python


The Python programming language provides the keyword def to create functions. The
general syntax to create functions is as follows.

Syntax
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...

❖ The list of parameters in a function definition needs to be separated with a comma.


❖ In Python, every function returns a None value by default. However, we can return our
value.
❖ Every function requires a function call to execute its code.

Calling a function in Python


In Python, we use the name of the function to make a function call. If the function requires
any parameters, we need to pass them while calling it.
The general syntax for calling a function is as follows.

Syntax
function_name(parameter_1, parameter_2,...)

Program to demonstrate a Function without arguments


def display():
print("Function without arguments")

display()

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

When we run the above example code, it produces the following output.

Write a user defined function to add 2 numbers and display their sum.

#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)

#function call
addnum()

When we run the above example code, it produces the following output.

WAP using a user defined function that displays sum of first n natural
numbers, where n is passed as an argument.
#function definition
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum+i
print("The sum of first",n,"natural numbers is: ",sum)

num = int(input("Enter the value for n: "))


sumSquares(num) #function call

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Write a program using a user defined function calcFact() to calculate and


display the factorial of a number num passed as an argument

def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)

num = int(input("Enter the number: "))


calcFact(num)

When we run the above example code, it produces the following output.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Program to Find the Area of Trapezium Using the Formula


Area = (1/2) * (a + b) * h Where a and b Are the 2 Bases of Trapezium and h Is the
Height

def area_trapezium(a,b,h):
area=0.5*(a+b)*h
print("Area of a Trapezium is ",area)
def main():
area_trapezium(10,15,20)
if __name__ == "__main__":
main()

When we run the above example code, it produces the following output

2.6 The return statement and void Function


In Python, it is possible to compose a function without a return statement. Functions like
this are called void, and they return None

A function may or may not return a value when called. The return statement returns
the values from the function.
A return statement consists of the return keyword followed by an
optional return value.

If an expression list is present, it is evaluated, else None is substituted


def add(a, b):
result = a + b
return result

print(add(2, 2))
Output : 4
9

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Armstrong Number : The sum of cubes of each digit is equal to the number itself.

For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.

Program to Check If a 3 Digit Number Is Armstrong Number or Not

num = int(input("Enter a number: "))


sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp = temp//10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

When we run the above example code, it produces the following output

Enter a number: 121


121 is not an Armstrong number
Enter a number: 407
407 is an Armstrong number
2.6 Scope and Lifetime of Variables
The part of the program where a variable is accessible can be defined as the scope of that
variable. A variable can have one of the following two scopes:
A variable that has global scope is known as a global variable and a variable that has a local
scope is known as a local variable.
10

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.6.1. Global Variable

A variable that is defined outside any function or any block is known as a global variable. It
can be accessed in any functions defined onwards. Any change made to the global variable
will impact all the functions in the program where that variable can be accessed.
2.6.2 Local Variable
A variable that is defined inside any function or a block is known as a local variable. It can
be accessed only in the function or a block where it is defined. It exists only till the function
executes.

Program to Demonstrate the Scope of Variables

num1 = 5 #globalvariable
def myfunc():
# variable num1 outside the function
print("Accessing num =",num1)
num = 10 #localvariable
print("num reassigned =", num)
myfunc()
print("Accessing num outside myfunc",num1)

When we run the above example code, it produces the following output

11

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Calculate and Add the Surface Area of Two Cubes. Use Nested Functions

def add_cubes(a, b):


def cube_surfacearea(x):
return 6 * pow(x, 2)
return cube_surfacearea(a) + cube_surfacearea(b)

def main():
result=add_cubes(2, 3)
print("The surface area after adding two Cubes
is",result)

if __name__ == "__main__":
main()

When we run the above example code, it produces the following output

2.7 Default Parameters / Default Arguments


Python allows assigning a default value to the parameter. If the function is called with
value then, the function executed with provided value, otherwise, it executed with the
default value given in the function definition.

def addition(num1, num2= 9, num3= 5):


return num1 + num2 + num3

result = addition(10, 20, 30)


print("sum=",result)
result = addition(10, 20) # 3rd argument uses default value
print("sum=",result)
result = addition(10) #2nd and 3rd argument uses default value
print("sum=",result)
12

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

When we run the above example code, it produces the following output

2.7 Keyword Arguments


The keyword argument is an argument passed as a value along with the parameter name
(kwarg = value).
When keyword arguments are used, we may ignore the order of arguments. We may pass
the arguments in any order because the Python interpreter uses the keyword provided to
match with the respective parameter.

def student_info(rollNo, name, group):


print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}')
print(f'Group : {group}')

student_info(name='Raju', rollNo=111, group='MSDs')

13

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.8 *args and **kwargs


In Python, we can pass a variable number of arguments to a function using special symbols.
There are two special symbols:
1. *args (Non Keyword Arguments)
2. **kwargs (Keyword Arguments)
We use *args and **kwargs as an argument when we are unsure about the number of
arguments to pass in the functions.
Python has *args which allow us to pass the variable number of non keyword arguments
to function. In the function, we should use an asterisk (*) before the parameter name to
pass a variable number of arguments.
Example program on *args

def largest(*numbers):
return max(numbers)

print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))

When we run the above example code, it produces the following output

Python has **kwargs which allows us to pass the variable length of keyword arguments
to the function. In the function, we use the double-asterisk (**) before the parameter
name to denote this type of argument.

14

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Example program on **kwargs

def Student_info(**kwargs):
print(kwargs)

Student_info(name="Raju",rollno=111,group="MSDs")

When we run the above example code, it produces the following output

2.9 Command Line Arguments


A Python program can accept any number of parameters from the command line. Python
sys module stores the command line arguments into a list, we can access it
using sys.argv

import sys
print("Number of arguments:",len(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)

Save above code Filename.py (Ex:- Command.py)

15

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

3. Strings
A string is a sequence of characters which is enclosed in quotes. In Python, A string can be
created by enclosing one or more characters in single, double or triple quote.. The Python
treats both single quote and double quote as same.
For example, the strings 'Hi Friend' and "Hi Friend" both are same.
3.1 Creating and Storing Strings
In Python, creating string variables is very simple as we need to assign a string value to a
variable.
str1 = 'Hello World!'
str2 = "Hello World!"
str3 = """Hello World!
welcome to the world of Python"""
str4 = '''Hello World!
welcome to the world of Python'''

3.2 Accessing Characters in a String


• Each individual character in a string can be accessed using a technique called
indexing.
• The index specifies the character to be accessed in the string and is written in square
brackets ([ ]).
• The index of the first character (from left) in the string is 0 and the last character is
n-1 where n is the length of the string.
• If we give index value out of this range then we get an IndexError. The index must
be an integer (positive, zero or negative).

16

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

• The index can also be an expression including variables and operators but the
expression must evaluate to an integer

• Python allows an index value to be negative also. Negative indices are used when
we want to access the characters of the string from right to left.
• Starting from right hand side, the first character has the index as -1 and the last
character has the index –n where n is the length of the string.

17

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

3.2 String is Immutable


A string is an immutable data type. It means that the contents of the string cannot be
changed after it has been created. An attempt to do this would lead to an error.

3.3 STRING OPERATIONS


Python allows certain operations on string data type, such as concatenation, repetition,
membership and slicing.
3.3.1 Concatenation
To concatenate means to join. Python allows us to join two strings using concatenation
operator plus which is denoted by symbol +.

3.3.2 Repetition
Python allows us to repeat the given string using repetition operator which is denoted by
symbol *

Note: str1 still remains the same after the use of repetition operator

18

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

3.3.3 Membership
Python has two membership operators 'in' and 'not in'. The 'in' operator takes
two strings and returns True if the first string appears as a substring in the second string,
otherwise it returns False.

The 'not in' operator also takes two strings and returns True if the first string does
not appear as a substring in the second string, otherwise returns False.

3.3.4 Slicing
In Python, to access some part of a string or substring, we use a method called slicing. This
can be done by specifying an index range.
To access substring from a string, we use string variable name followed by square brackets
with starting index , ending index and Step of the required substring.

19

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

#first index > second index results in an #empty '' string

If the first index is not mentioned, the slice starts from index and If the second index is not
mentioned, the slicing is done till the length of the string.

The slice operation can also take a third index that specifies the ‘step size’. For
example, str1[n:m:k], means every kth character has to be extracted from the string
str1 starting from n and ending at m-1. By default, the step size is one.

Negative indexes can also be used for slicing. If we ignore both the indexes and give step
size as -1 , str1 string is obtained in the reverse order.

20

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

3.3.4 Joining
The join() string method returns a string by joining all the elements of an iterable (list,
string, tuple), separated by a string separator.

3.4 Traversing A String


We can access each character of a string or traverse a string using for loop and
while loop
String Traversal Using for Loop:

str1 = 'Hello World!'


for ch in str1:
print(ch)
String Traversal Using while Loop:

str1 = 'Hello World!'


index = 0
while index < len(str1):
print(str1[index])
index += 1
3.5 String Methods and Built-In Functions

Method Description Example


>>> str1 = 'Hello World!'
Returns the length of the
len() >>> len(str1)
given string 12
Returns the string with first letter >>> str1 = 'hello WORLD!'
title() of every word in the string in >>> str1.title()
uppercase and rest in lowercase 'Hello World!'
Returns the string with all >>> str1 = 'hello WORLD!'
lower() Uppercase letters converted to >>> str1.lower()
lowercase 'hello world!'
Returns the string with all >>> str1 = 'hello WORLD!'
upper() lowercase letters converted to >>> str1.upper()
uppercase 'HELLO WORLD!'
Returns number of times >>> str1 = 'Hello World!
Hello Hello'
count(str, substring str occurs in the
>>>str1.count('Hello',12,25
start, end) given string. If we do not give start )
index and end index then 2
21

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

searching starts from index 0 and >>> str1.count('Hello')


ends at length of the string 3

>>> str1 = 'Hello World!


Hello Hello'
Returns the first occurrence of
>>>
index of substring str occurring in str1.find('Hello',10,20)
the given string. If we do not give 13
find
start and end then searching starts >>>
(str,start, str1.find('Hello',15,25)
from index 0 and ends at length of
end) 19
the string. If the substring is not
>>> str1.find('Hello')
present in the given string, then
0>
the function returns -1 >> str1.find('Hee')
-1
>>> str1 = 'Hello World!
Hello Hello'
Same as find() but raises an >>> str1.index('Hello')
Index (str,
exception if the substring is not 0
start, end) >>> str1.index('Hee')
present in the given string
ValueError: substring not
found
>>> str1 = 'Hello World!'
>>>str1.endswith('World!')
Returns True if the given string True
endswith() ends with the supplied substring >>> str1.endswith('!')
otherwise returns False True
>>> str1.endswith('lde')
False
>>> str1 = 'Hello World!'
Returns True if the given string >>> str1.startswith('He')
startswith() starts with the supplied substring True
otherwise returns False >>> str1.startswith('Hee')
False
>>> str1 = 'HelloWorld'
Returns True if characters of the >>> str1.isalnum()
given string are either alphabets True
or numeric. >>> str1 = 'HelloWorld2'
isalnum() If whitespace or special symbols >>> str1.isalnum()
are part of the True
given string or the string is empty >>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
it returns False False
>>> str1 = 'hello world!'
Returns True if the string is >>> str1.islower()
non-empty and has all lowercase True
>>> str1 = 'hello 1234'
alphabets, or has at least one
islower() >>> str1.islower()
character as lowercase alphabet True
and rest are non-alphabet >>> str1 = 'hello ??'
characters >>> str1.islower()
True

22

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

>>> str1 = '1234'


>>> str1.islower()
False
>>> str1 = 'Hello World!'
>>> str1.islower()
False
>>> str1 = 'HELLO WORLD!'
>>> str1.isupper()
True
>>> str1 = 'HELLO 1234'
Returns True if the string is >>> str1.isupper()
non-empty and has all uppercase True
>>> str1 = 'HELLO ??'
alphabets, or has at least one
isupper() >>> str1.isupper()
character as uppercase character True
and rest are non-alphabet >>> str1 = '1234'
characters >>> str1.isupper()
False
>>> str1 = 'Hello World!'
>>> str1.isupper()
False
>>> str1 = ' \n \t \r'
Returns True if the string is >>> str1.isspace()
non-empty and all characters are True
isspace() >>> str1 = 'Hello \n'
white spaces (blank, tab,
newline, carriage return) >>> str1.isspace()
False
Returns True if the string is >>> str1 = 'Hello World!'
non-empty and title case, i.e., the >>> str1.istitle()
True
istitle() first letter of every word in the >>> str1 = 'hello World!'
string in uppercase and rest in >>> str1.istitle()
lowercase False
Returns the string after removing >>> str1 = ' Hello World! '
lstrip() the spaces only on the left of the >>> str1.lstrip()
string 'Hello World! '
Returns the string after removing >>> str1 = ' Hello World!
'
rstrip() the spaces only on the right of the >>> str1.rstrip()
string ' Hello World!'
Returns the string after removing >>> str1 =' Hello World!
'
strip() the spaces both on the left and the >>> str1.strip()
right of the string 'Hello World!'
>>> str1 = 'Hello World!'
>>> str1.replace('o','*')
'Hell* W*rld!'
replace(olds Replaces all occurrences of old
>>> str1 = 'Hello World!'
tr, newstr) string with the new string >>>str1.replace('World','Co
untry')
'Hello Country!'

23

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

>>> str1 = 'Hello World!


Hello'
>>>
str1.replace('Hello','Bye')
'Bye World! Bye'
>>> str1 = ('HelloWorld!')
Returns a string in which the >>> str2 = '-'
join() characters in the string have been #separator
joined by a separator >>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'
Partitions the given string at the >>> str1 = 'India is a
first occurrence of the substring Great Country'
(separator) and returns the string >>> str1.partition('is')
partitioned into three parts.
('India ', 'is', ' a Great
1. Substring before the separator
partition() Country')
2. Separator
3. Substring after the separator >>> str1.partition(‘are’)
If the separator is not found in the
string, it returns the whole string (‘India is a Great
itself and two empty strings Country’,’ ‘,’ ‘)
Returns a copy of the string with >>>str='hello world!'
capitalize() its first character capitalized and >>>str.capitalize()
the rest lowercased 'Hello world!'
returns a string where all the
characters are in lower case. It is >>>str="HELLO world"
sasefold() similar to the lower() method, but >>>str.casefold()
the casefold() method converts 'hello world'
more characters into lower case.

Write Python Program to Convert Uppercase Letters to Lowercase and Vice Versa

def case_conversion(string):
str1=str()
for ch in string:
if ch.isupper():
str1+=ch.lower()
else:
str1 += ch.upper()
print("The modified string is ",str1)
def main():
str2=input("Enter a String :")
case_conversion(str2)
if __name__=="__main__":
main()
Output :
Enter a String : Hello WORLD
The modified string is hELLO world
24

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Example Program on String Methods

str1 = ‘ hello World! ‘


print(“String in Uppercase :”, str1.upper())
print(“String in Lower case :”, str1.lower())
print(“Capitalized String :”, str1.capitalize())
print(“String with first letter :”,str1.title())
print(“String alphanumeric :”,str1.isalnum())
print(“String in lowercase :“,str1.islower())
print(“String in uppercase :“,str1.isupper())
print(“Swapcase :“,str1.swapcase())
print(“Right Strip of String :“,str1.rstrip())
print(“Left Strip of String :“,str1.lstrip())
print(“Right & Left Strip of String :“,str1.strip())

Output :
String in Uppercase : HELLO WORLD!
String in Lower case : hello world!
Capitalized String : hello world!
String with first letter : Hello World!
String alphanumeric : False
String in lowercase : False
String in uppercase : False
Swapcase : HELLO wORLD!
Right Strip of String : hello World!
Left Strip of String : hello World!
Right & Left Strip of String : hello World!

3.6 Formatting Strings

Python f-string is the newest Python syntax to do string formatting. It is available since
Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error
prone way of formatting strings in Python.

The f-strings have the f prefix and use {} brackets to evaluate values.

The format strings will contain the curly braces { } and the format() method will use those
curly braces { } as placeholders to replace with the content of the parameters.

25

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

name = 'Raju'
age = 23
print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
Output :
Raju is 23 years old
Raju is 23 years old
Raju is 23 years old

3.7 Function Prototypes:


Based on the data flow between the calling function and called function, the functions
are classified as follows...
• Function without Parameters and without Return value
• Function with Parameters and without Return value
• Function without Parameters and with Return value
• Function with Parameters and with Return value

3.7.1 Function without Parameters and without Return value


• In this type of functions there is no data transfer between calling function and called
function.
• Simply the execution control jumps from calling-function to called function and
executes called function, and finally comes back to the calling function.
• For example, consider the following program..

def add(): Output :


a=int(input("enter a")) enter a 10
b=int(input("enter b")) enter b 20
c=a+b 30
print(c)
add()

3.7.2 Function with Parameters and without Return value

• In this type of functions there is data transfer from calling-function to called function
(parameters) but there is no data transfer from called function to calling-function
(return value).
• The execution control jumps from calling-function to called function along with the
parameters and executes called function, and finally comes back to the calling
function.

• For example, consider the following program...


26

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

def add(a,b):
c=a+b
print(c) Output :
enter a 10
enter b 20
a=int(input("enter a")) 30
b=int(input("enter b"))
add(a,b)

3.7.3 Function without Parameters and with Return value

• In this type of functions there is no data transfer from calling-function to called-


function (parameters) but there is data transfer from called function to calling-
function (return value).
• The execution control jumps from calling-function to called function and executes
called function, and finally comes back to the calling function along with a return
value.
• For example, consider the following program...

def add():
a = int(input("enter a"))
b = int(input("enter b"))
c = a + b Output :
return c enter a 10
enter b 20
c = add() 30
print(c)

3.7.4 Function with Parameters and with Return value

• In this type of functions there is data transfer from calling-function to called-


function (parameters) and also from called function to calling-function (return
value).
• The execution control jumps from calling-function to called function along with
parameters and executes called function, and finally comes back to the calling
function along with a return value

def add(a,b):
c = a + b Output :
return c enter a 10
a = int(input("enter a")) enter b 20
b = int(input("enter b")) 30
c = add(a,b)
print(c)

27

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Unit-II Questions
1. Explain 4 different function prototypes with an example programs
2. Explain built in functions with suitable examples
3. Write a short note on return statement in function with an example
program.
4. Explain Commonly used modules with an example programs
5. Write a short note on formatted strings
6. Explain built-in functions with examples
7. Differentiate between local and global variables with suitable examples
8. Define Function. Explain with syntax how to create a used-defined functions
and how to call the user -defined functions / how to call user defined
functions from the main function
9. Explain about default arguments , *args and **kwargs
10. Write a short note on Command line arguments with an example program
11. Explain strings in detail (Creating and accessing )
12. Explain string operations in detail.
13. Explain string methods with an example programs

28

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com

You might also like