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

Grade 11 Syllabus

This document provides an overview of Python programming, covering its features, data types, operators, and basic syntax. It explains concepts such as tokens, variables, literals, and expressions, as well as the different types of operators and their precedence. Additionally, it discusses input/output functions, type conversion, and debugging methods in Python.

Uploaded by

vedeshadaikkalam
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)
4 views

Grade 11 Syllabus

This document provides an overview of Python programming, covering its features, data types, operators, and basic syntax. It explains concepts such as tokens, variables, literals, and expressions, as well as the different types of operators and their precedence. Additionally, it discusses input/output functions, type conversion, and debugging methods in Python.

Uploaded by

vedeshadaikkalam
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/ 58

Basics of Python programming:

Introduction to Python -Python is a general-purpose Object Oriented Programming


language, High-level language Developed in late 1980 by Guido van Rossum at National
Research Institute for Mathematics and Computer Science in the Netherlands. It is an
Open Source Scripting language and is Case-sensitive language .
Features of Python

terpreter.

relatively simple structure.


-sensitive. For example, NUMBER and number are not same in Python.
ns it can run on various operating
systems and hardware platforms.

applications are built using Python.


on for blocks and nested blocks
There are two ways to use the Python interpreter:
a) Interactive mode b) Script mode

Tokens Smallest individual unit in a program is known as token. Tokens are of


following types-
keyword, identifier, literal, operator, punctuator
Keyword- Keywords are reserved words. Each keyword has a specific meaning to the
Python interpreter, and we can use a keyword in our program only for the purpose for
which it has been defined.
Identifier- Identifiers are names used to identify a variable, function, or other entities
in a program. The rules for naming an identifier in Python are as follows:
should begin with an uppercase or a lowercase alphabet or an underscore
sign (_). This may be followed by any combination of characters a z, A Z, 0 9 or
underscore (_). Identifier cannot start with a digit.
short and meaningful).

Some valid identifiers are- sno , nam1, f_no, _a , false


Invalid identifiers are First number , f.no, 1num , for
Variables- A variable in a program is uniquely identified by a name . Variable is an
object / an item or element that is stored in the memory. Variables must always be
assigned values before they are used in expressions. For example
Num=10

A variable has three main components: Identity , Type and a Value .


Identity refers to the address in the memory. The address of an object can be
checked using the method id().
Literal-Literals are data items that have a fixed value. Python supports several kinds
of literals:
String Literal
Numeric Literals
Boolean Literals
Special Literals None
35
String Literal is a collection of character(s) enclosed in a double or single quotes. It can
be either Single line strings or Multiline Strings

Numeric literals -
Integer Literals: it contain at least one digit and must not contain decimal point. It may
contain (+) or (-) sign.
Floating point Literals: Also known as real literals. Real literals are numbers having
fractional parts.
Complex number Literals: Complex number in python is made up of two floating.
Boolean literals in Python is used to represent one of the two Boolean values i.e. True or
False
Python has one Special literal, which is None. It indicates absence of value. In other
languages it is knows as NULL
Punctuators.-Punctuators are symbols that are used in programming languages to
organize sentence structure, and indicate the rhythm and emphasis of expressions,
statements, and program structure.

Operator - An operator is used to perform specific mathematical or logical operation


on values. The values that the operators work on are called operands. For example, in
the expression 25 + fno, the value 25, and the variable fno are operands and the + (plus)
sign is an operator. Python supports several kinds of operators. They are -
Arithmetic Operator
Relational Operator
Logical operators
Assignment Operator
Identity Operators
Membership Operator
1. Arithmetic Operator

Operator Operation Description Example


+ Addition Adds two numbers >>>a=10
>>>b=4
>>>a+b
4
- Subtraction Subtract the operand >>>a=10
on the right from the >>>b=4
operand on the left >>>a-b
6
* Multiplication Multiplies the two values >>>a=10
>>>b=5
>>>a*b
50
/ Division Divides the operand >>>a=10
on the left with the >>>b=5
operand on the >>>a/b
right 2

36
% Modulus Divides the operand on >>>a=10
the left with the >>>b=3
operand on the right >>>a%b
and returns the 1
remainder
// Floor Division Floor division. To >>>a=10
find the integer part >>>b=6
of the quotient when >>>a/b
one number is 1
divided by the other.
The result is always
the largest integer
less than or equal to
the actual quotient.
** Exponent To raise a number to >>>a=2
the power of another >>>b=3
number. >>>a**
b
8
Relational Operator
Operator Operation Description Example
== Equals to Compares two values. If both are equal >>>x=5
returns true else returns False >>>y=4
>>>z=4
>>>x==y
False
>>>y==z
True
!= Not Equals to Compares two values. If both are not >>>x!=y
equal returns true else returns False True
>>>y!=z
False
> Greater Than If the value of the left operand is greater >>>y>x
than operand on the rightside of False
operator then returns true else return >>>x>z
False True
< Less than If the value of the left operand is smaller >>>y<z
than operand on the rightside of True
operator then returns True >>>x<y
else return False False
>= Greater than or If the value of the left operand is greater >>>z>= y
equal to than or equal to operand on the right True
side of operator then >>> y>= x
returns True else return False False
<= Less than or If the value of the left operand is smaller >>>x<= y
equal to than operand on the rightside of False
operator then returns true else return >>>z <= x
False True
37
Logical operators
Operators Description Example
And Combines two conditions and returnsTrue if >>>a=6
both conditions are True else returns False >>>b=5
>>>a==6 and b==5
True
>>>a1==10 and b==5
False
Or Combines two conditions and returns True if any >>>a==6 or b==0
condition is True else returnsFalse True
>>>a==0 or b==4
False
Not Negates a condition and returns True if the >>>not (a==0)
condition is False, otherwise returns False. True
>>>not (b==5)
False
Assignment Operator
Operator Description Example (x=2,
y=5)
= Assigns value from right side operand to left side >>>z=x+y
operand >>>z
7
+= It adds the value of right-side operand to the >>>x+=2
left-side operand and assigns the result to the
>>>x
left-side operand
4

-= It subtracts the value of right-side operand from >>>x-=2


the left-side operand and assigns the result to >>>x
left-side operand 0

*= It multiplies the value of right-side operand >>>x*=5


with the value of left-side operand and assigns
>>>x
the result to left-side operand
10

/= It divides the value of left-side operand by the >>>x/=y


value of right-side operand and assigns the
>>>x
result to left-side operand
0.4

%= It performs modulus operation using two >>>x%=2


operands and assigns the result to left-side
>>>x
operand
0

//= It performs floor division using two operands >>>x//=3


and assigns the result to left-side operand >>>x
0

38
**= It performs exponential (power) calculation on >>>x**=3
operators and assigns value to the left-side
>>>x
operand 8

Identity operator
Operator Description Example
Is Evaluates True if the variables on either side >>> num1 = 5
of the operator point towards the same >>> type(num1) is int
memory location and False otherwise. var1 True
is var2 results to True if id(var1) is equal to >>> num2 = num1
id(var2) >>> id(num1)
1433920576
>>> id(num2)
1433920576
>>> num1 is num2
True
is not Evaluates to False if the variables on either >>> num1 is not num2
side of the operator point to the same False
memory location and True otherwise. var1
is not var2 results to True if id(var1) is not
equal to id(var2)
6. Membership Operator
Operators Description Example
In It return True in case value exists in >>>N=[5,7,1]
sequence, otherwise false. >>>1 in N
True
>>> 4 in N
False
not in return True if value does not exists in the >>>N=[4,8,7]
sequence, else false. >>>4 not in L
False
>>> 0 not in L
True
Precedence of Operators:
The order in which the operators are executed in an expression is called the operator
precedence. Operator precedence of some common operators are given below:

39
Comments- Comments are used to add a remark or a note in the source code. they
are not executed by interpreter. They are added with the purpose of making the source
code easier for humans to understand. In Python, a comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment.

Data Types-
Data Type specifies which type of value a variable can store. type () function is used to
determine a variable's type in Python. Data type in Python can be categorized as
follows:
1. Number: Number data type stores numerical values. A feature Python is that there
is no need to declare a numeric value to define its type. Python can easily
differentiate one data typefrom another when you write and run your statement.
(a) int(integer): Integer represents whole numbers without any fractional part. They
can be positive or negative and have unlimited size in Python. Example: -6, 468, 0, 4, -
43.
(b) float(floating point number): Floating point numbers denote real numbers or
floating point values (i.e., numbers with fractional part). Example: 3.14, 565.34, 0.76, 4.0
(c)Complex Numbers: Complex numbers in Python are made up of pairs of real and
imaginary numbers. They take the + or +
a = complex(50) # convert 50 to a real part val and zero imaginary part
b=complex(87,54) #convert 87 with real part and 54 as imaginary part
print(b)

Output :-
(5+0j)
(101+23j)
2. str(string):A string is a sequence of characters that can be a combination of letters,
numbers and special symbols, enclosed within quotation marks, single, double, or
triple or or These quotes are not part of the string.
3. Boolean: Boolean data type represents one of the two possible values, True or False.
Any expressionwhich can be True or False has the data type bool.
4. None: This is a special data type with a single value. It is used to signify the absence
of value/condition evaluating to False in a situation. It is represented by None.
5. List: A list is a collection of values or an ordered sequence of values/items. The
items in a listcan be of any type such as string, integers, float, objects or even a list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Example: >>> A = [6,8,2,9,100]
>>>print( A )
[6,8,2,9,100]
6.Tuple: Tuple is another sequence data type similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists however, tuples are enclosed
within parentheses. Elements in a tuple need not be of the same type, they can be
heterogeneous.
Example: >>> T = ( 80,40,25, 30, 50 )
>>>print( L )
( 80,40,25, 30, 50)

40
7.Dictionary: -Python-dictionary is an unordered collection of items where each item
is a key-value pair. We can also refer to a dictionary as a mapping between a set of keys
and set of values. The items of a dictionary are enclosed within curly braces and items
are separated by commas.The key value pairs are separated by colon (:).
Example: Dict = 96, : 88, : 91 }

Mutable and Immutable Types


Mutable data types: Data types where the value can be changed in place. Example:
dictionary, sets, lists etc.
Immutable data types: Data types where the values cannot be changed in place.
Example: integer, float, string, tuples etc.

Expression- An expression is defined as a combination of constants, variables, and


operators. An expression always evaluates to a value. A value or a standalone variable is
also considered as an expression but a standalone operator is not an expression. Some
examples of valid expressions are given below.
(i) 750 (iv) 5.0 + 9.54 (ii) avg (v) 23/3 -5 * 7 +(14 -2*a) (iii) num 20 (iv) "India" +
"Russia"

Statement- In Python, a statement is a unit of code that the Python interpreter can
execute. For example
a=50
x=sum(4,5)

input/output - input() function is used for taking the user input. The input()
function prompts the user to enter data. It accepts all user input as string.
name = input("Enter your name: ")
print() function is used to output data to the screen. It evaluates the expression before
displaying it on the screen. The print() outputs a complete line and then moves to the
next line for subsequent output. The syntax for print() is:
print(value [, ..., sep = ' ', end = '\n'])
print( "Bikaner")

Type Conversion: It is the process of converting the value of one data type to
another.

There are two types of type conversions in Python:


1. Implicit Type Conversion: In this, Python automatically converts value from one
data type to another Example:
>>> a=2 # a is integer
>>> b=55.4 # b is float
>>> c=a+b # c will be float
>>> print(c) # will print 57.4

2. Explicit Type Conversion or type casting: In this type of conversion, programmer


forces to convert data type of an object to required data type. functions int (), float () or
str ( ) etc. can be used. Example:
>>> a=2 # a is integer
>>> b=55.4 # b is float
>>> c=int(a+b) # c is int
>>> print(c) # will print 57

41
Debugging- The process of identifying and removing errors or mistakes from a
program is called debugging and the mistakes known as errors. Errors can be
categorized as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
1. Syntax Error:
If a statement is not written as per syntax/ rules of python, syntax errors are there and
interpreter shows error message(s) and stops the execution there. Example 1:
#syntax error as right double quote is missing
Example 2: #syntax error due to P is capital

2. Logical Error:
Logical errors are the most difficult to find and fix. These types of error is caused due to
wrong logic. No syntax error /error message will be there.
Example:
x=5
y = 10
m=x+y
print x and y = results wrong as used + instead of *
3.Runtime Error:
A runtime error causes abnormal termination of program while it is executing. In this
error statement is correct syntactically, but the interpreter cannot execute it. Runtime
errors do not appear until after the program starts running or executing. For example, a
statement having division operation in program, if denominator value is zero then it
will give a runtime error by

42
Flow of Control
The order of execution of the statements in a program is known as flow of control.
Control statements are used to control the flow of execution depending upon the
specified condition/logic. There are three types of control /flow statements-
1. Sequential flow
2. Conditional Flow
3. Iterative flow

Sequential flow- It is the concept, where Python executes one statement after another
from beginning to the end of the program.
Conditional / Decision making statement-Decision making statement used to control
the flow of execution of program depending upon condition. Following conditional
statements available in python -
if statement
if-else statement
if-elif- else statement
Nested if statement
if statement-In this it checks the condition and execute the statement if the condition is
true and do nothing if the condition is false.
Syntax:
if condition:
Statements
Example-
x=1
if(x==1 ):

if-else statement-if with else is used to test the condition and if the condition is True it
perform /execute true block otherwise false block.
Syntax:
if condition:
Statements #True Block
else:
Statements # False block
Example-
num = int(input("Enter a number= "))
if (num%2==0):
print("even number ")
else:
print("odd number")
if-elif- else statement-In this variant of if multiple chain of condition is to be checked.
Each elif must be followed by condition: and then statement for it. After every elif we
can give else which will be executed if all the condition evaluates to false
Syntax:
if condition:
Statements
elif condition:
Statements
elif condition:
Statements
else:
Statement
43
Nested if statement-
it. Mostly used in a situation where we want different else for each condition. Syntax:
if condition1:
if condition2:
statements
else:
statements
elif condition3:
statements
else:
statements

Example:
num = float (input ("Enter a number: "))
if num>= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Iterative statements /Loop: To carry out repetition of statements Python provide


2 loop statements- for loop and while loop.

for loop- This loop is used to iterate over a range of values or a sequence. The for loop
is executed for each of the items in the range. These values can be either numeric, or,
they can be elements of a data type like a string, list, or tuple.
Syntax:
for val in sequence:
statements #body of loop
Example-1
city=["Bikaner","Jodhpur,"Jaipur","Sikar"]
for i in city:
print(i)

Example-2 (print all the natural number from 1 to 10)


for i in range(1,11):
print(i)

Usage of Range()-
It is used to create a list containing a sequence of integers from the given start value up
to stop value (excluding stop value), with a difference of the given step value. The range
() is a built-in function in Python. Syntax of range () function is:
range([start], stop[, step])

range (10) will generate set of values from 0-9


range (1,10,2) will produce [1,3,5,7,9]

True

True
44
for i in range (5,3,-1):
print(i)
for i in range (3,5):
print(i)
While loop- It is used to execute a block of statement as long as a given condition is true
and when the condition become false, the control will come out of the loop. The
condition is checked every time at the beginning of the loop.
Syntax
while (condition):
statements # body of loop
example-1
x = 10
while (x <= 20):
print(x)
x=x+1

Example-2
x=1
while (x < 3):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)

Jump Statements- These statements are used to transfer the program's flow from one
location to another. There are two types of jump statements -.
1. break
2. continue
Break- The break statement terminates the current loop and resumes execution of the
statement following that loop.
Example-
for I in range(1,100):
if i == 10:
break
print(i) # the code will print only 1 to 9
Continue- The continue statement skips the current execution of loop and jump for
next execution of the loop.
Example-
for I in range(1,100):
if i == 10:
continue
print(i) # the code will print 1 to 99 without 10
pass -This statement does nothing but can be used if no action in a statement.
for i in range (1,100):
if(i >=50):
pass
else:
print(i)

45
==================================================================
Exercises
(MCQ type Question 1 Marks)
1. Who developed Python Programming Language?
a) Wick van Rossum b) Rasmus Lerdorf
c) Guido van Rossum d) Niene Stom
Answer: c
2. Which of the following is the correct extension of the Python file?
a) .python b) .pys
c) .py d) .p
Answer: c
3 What will be the value of the following Python expression?
1 + 10 % 4
a) 3 b) 2
c) 11 d) 1
Answer: a
4. Which of the following character is used to give single-line comments in Python?
a) @ b) #
c) ! d) /*
Answer: b
5. Which one of the following is not a keyword in Python language?
a) for b) evals
c) while d) false
Answer: d
6. What will be the output of the following Python program?
i=1
while i < 5:
i += 1
print(i)
a) 5 b) 0
c) 1 d) none of the mentioned
Answer:a
7. run tyme error in a code means:
(a)You have not used correct logic.
(b) There was error while running the program.
(c) There is an error with your typing and code structure
(d) None of above.
Answer: b
8. Which of the following is not a core data type in Python programming?
a) Tuples b) Lists
c) Class d) Dictionary
Answer: c
9. What will be the output of the following Python code?
x = 'abcd'
for i in x:
print(i.upper())
a) a B C D b) a b c d
c) error d) A B C D
Answer: d
10.What will be the output of the following Python statement?
>>>"a"+"bc"
a) bc b) abc
c) a d) bca
Answer: b
46
(VSA type Question 2 Marks)
1. What are data types? How are they 2. What are immutable and mutable
important? types? List immutable and mutable
Answer = representation of many types types of python.
of data in by provided facilities is called Answer = immutable type :- those
data type . types whose value never change is
Example = integer, string , list etc. known as immutable type.
They are play very important role in Example = integer , string , Boolean,
programming because without any tuples , e.c.t
data of program , program can cause Mutable type: - those type whose value
error , so program needed data can be change is known as mutable
type.Example = list, dictionary, set
3. What are tokens in Python? How 4. What will the result given by the
many types of tokens are allowed in following ?
python? Exemplify your answer. (a)type(6+3)
Answer =Token are smallest individual (b)type(6-3)
unit in a program. (c)type(6*3)
Type of tokens (d)type(6/3)
keywords : False, True, for, while (e)type(6//3)
identifiers : a, A, lst, dic (f)type(6%3)
Answer =
operator : +, -, /, *, **, %, // (a)int (b)int (c)int
punctuators :&, ^, ?, #, @, ! (d)float (e)int (f)int

5. What are variables? How are they 6. In Python, strings are immutable
important for a program? while lists are mutable. What is the
Answer =Variable is a label that can difference?
used in process of program. it can Answer =(i) In consecutive locations,
contain numeric values, character, strings store the individual characters
string is called variable. while list stores the references of its
Variable play very important role in elements
programming because they enable (ii) Strings store single type of
programmers to write flexible elements - all characters while lists can
programs. without variable we can not sore elements belonging to different
enter the data directly in the program. types.

7. What is a cross-platform software? 8. How are these numbers different


Answer =Cross-platform software from one another? 33, 33.0, 33j, 33 +j
means that software that can work Answer --
easily in all type of operating system. 33 = integer
Example windows, Linux, 33.0=floating point number
smartphone etc. 33j = complex number
33+j = complex number
9. What is the difference between 10. What is debugging?
implicit type conversion and explicit Answer= The process of identifying
type conversion? and removing errors or mistakes from
Answer = the basic difference between a program is called debugging and the
implicit and explicit type conversion is mistakes known as errors.
that implicit is taken care by compiler
itself , while explicit is done by the
programmer .

47
(Short answer type Question 2 Marks)

Q-1 Rewrite the following code Q-2 Find the output of the following code
fragments using for loop: segments:
i = 10 x = 40
while (i > 0) : y=x+1
print (i) x = 20, y + x
i -= 3 print (x, y)
Answer = Answer =
for i in range (10,0,-3): Output:
print (i) (20, 81) 41

Q-3 What will be the output Q-4 What will be the output produced by
produced by following code following code?
fragment (s)? (a)
X = 10 >>> str(print()) + "One"
X = X + 10 (b)
X=X-5 >>> str(print("hello")) + "One"
print (X) Answer =
X, Y = X- 2, 22 (a)
print (X, Y) 'NoneOne'
answer= (b)
5 hello
13 22 'NoneOne'
Q-5 Rewrite the following code Q-6 Find the output of the following code
fragment that saves on the number segments:
of comparisons: var = 7
if (a == 0) : while var > 0:
print ("Zero") print ('Current variable value: ', var)
if (a == 1) : var = var -1
print("One") if var == 3:
if (a == 2) : break
print ("Two") else:
if (a == 3) : if var == 6:
print ("Three") var = var -1
Answer = continue
if (a == 0) : print ("Good bye!")
print ("Zero") Answer :-
elif (a == 1) : Current variable value: 7
print("One") Current variable value: 5
elif (a == 2) : Good bye!
print ("Two") Current variable value: 4
elif (a == 3) :
print ("Three")
Q-7 How is break statement different Q-8 Find out the error(s) in following code
from continue? fragments:
Answer = a, b, c = 2, 8, 9
Break :- A break statement skips the print (a, b, c)
rest of the loop and jumps over to thec, b, a = a, b, c
statement following the loop. print (a; b; c)
answer=
Continue :- The continue statement a, b, c = 2, 8, 9
skips the rest of the loop statements print (a, b, c)

48
and causes the next iteration of the c, b, a = a, b, c
loop to take place. print (a, b, c)

Q-9 What is the purpose of range() Q-10 Write Pseudo code to calculate area of
function? Give one example. circle.
Answer :-It is used to create a list Answer:-
containing a sequence of integers t = input "Enter Radius of circle "
from the given start value up to stop Area = pi * r * r
value (excluding stop value), with a Display Area
difference of the given step value.
Example :-
for i in range(100) :
It will run from 0 to 99.
Q-11Find the output of the following Q-12 Find the output of the following code
code segments: segments:
a = 110 i = 0; sum = 0
while a > 100: while i < 9:
print(a) if i % 4 == 0:
a -= 2 sum = sum + i
Answer :- i=i+2
110 print (sum)
108 Answer :-
106 0
104 0
102 4
4
12
Q-13 Find the output of the following Q-14 Find the output of the following code
code segments: segments:
country = 'INDIA' for i in range(20,30,2):
for i in country: print(i)
print (i)
Answer :-
Answer :- 20
I 22
N 24
D 26
I 28
A
Q-15 Find the output of the following Q-16 What will be output produced by
code segments: following code? State reason.
for x in range(1,4): a=5-4-3
for y in range(2,5): b = 3 ** 2 ** 3
if x * y > 10: print(a)
break print(b)
print (x * y) Answer =
Answer :- Line 1:
2 a = -2
3 Line 2:
4 b = 3 ** 2 ** 3
4 = 3 ** 8
6 So for:
8 b = 6561
6
49
9
Q-17 Draw flow chart to calculate Q-18 Write algorithm to calculate simple
simple interest. interest.
Answer :-
1. Start
2. Input principal
3. Input rate
4. Input time
5. Simple interest principal * rate * time
6. Print simple interest
7. Stop

50
STRING IN PYTHON

Definition: String is a collection of characters. Strings can be created by enclosing


characters inside a single quote or double-quotes. Even triple quotes can be used in
Python but generally used to represent multiline strings. Python does not have a
character data type, a single character is simply a string with a length of 1.

Basics of String:
Strings are immutable means that the contents of the string cannot be changed
after it is created. At the same memory address, the new value cannot be stored.
Python does not allow the programmer to change a character in a string.
Example:
>>>str='jaipur'
>>>str[0]='J'
TypeError: 'str' object does not support item assignment
As shown in the above ex

ample, str string by


J displays a TypeError.
Each character has its index or can be accessed using its index.
String in python has two-
direction and -1, -2, -
Example:
0 1 2 3 4 5 6
T E A C H E R
-7 -6 -5 -4 -3 -2 -1

The index of string in forward direction starts from 0 and in backward direction
starts from -1.
The size of string is total number of characters present in the string. (If there are
n characters in the string, then last index in forward direction would be n-1 and
last index in backward direction would be n.)
String are stored each character in contiguous location.
The character assignment is not supported in string because strings are
immutable.

Accessing Characters in a String


As we know, string is a collection of characters and individual character can be accessed
by its position called index. Square brackets can be used to access elements of the string.

Example:

>>>s[1]
returns index 1 position
>>>s[-4]
returns index -4 position

Traversing a String: Access all elements of string, one character at a time.

51
for ch in s : for i in range(len(s)):
print(ch) print(s[i])

>>>len(s) # returns length of string.

String Operators:
A). String concatenation Operator: Concatenation means to join two values. In
Python, + symbol is used to concatenate the strings.
>>>name="Jay"
>>>msg="Hello "
>>>print(msg+name)
'Hello Jay' #concatenated string
Note: You cannot concate numbers and strings as operands with + operator.
Example:

It is invalid and generates an error.


B). String repetition Operator: It is also known as String replication operator.
Replication can be performed by using * operator between the string. It will repeat the
string n times, where n is the integer providedple:
>>>s="Ha"
>>> s*3
'HaHaHa' #Replication
Note:You cannot have strings as n=both the operands with * operator.
Example:
-int of type 'str'
It is invalid and generates an error.
C). Membership Operators: In and not in are two membership operators to find the
appearance of a substring inside the string.in Returns True if a character or a substring
exists in the given string; otherwise, False
not in - Returns True if a character or a substring does not exist in the given string;
otherwise, False
Example: >>> "T" in "TEACHER"
True
>>> "ea" in "TEACHER "
False
>>>"CH" not in "TEACHER "
False
D). Comparison Operators: These operators compare two strings character by
character according to their ASCII value. ASCII Values can be finding out by given
functions.
Characters ASCII (Ordinal) Value
48 to 57
65 to 90
97 to 122

Function Description
ord(<character>) Returns ordinal value of a
character
chr(<value>) Returns the corresponding
character

52
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
>>> ord('b')
98
>>> chr(65)
'A'

Slicing in Strings: Extracting a subpart from a main string is called slicing .It is done
by using a range of indices.
Syntax:
>>>string-name[start:stop:step]
Note: it will return a string from the index start to stop-1.
Example:
>>> s="TEACHER"
0 1 2 3 4 5 6
T E A C H E R
-7 -6 -5 -4 -3 -2 -1

>>> s[2:6:1]
'ACHE'
>>> s[6:1:-1]
'REHCA'
>>> s[0:10:2]
'TAHR'
>>> s[-8:-3:1]
'TEAC
>>> s[ : 6 : 1] # Missing index at start is considered as 0.
'TEACHE'
>>> s[2 : :2] # Missing index at stop is considered as last index.
'AHR'
>>> s[3:6: ] # Missing index at step is considered as 1.
'CHE'
>>> s[ : :-1]
'REHCAET'
>>> s[2: :]+s[ :2 :]
'ACHERTE'
>>> s[1: 5:-1]

Built-in functions of string:

s3
s4 s5=

53
S. Function Description Example
No.
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns the copy of the string with its >>> s1.capitalize()
first character capitalized and the rest 'Hello365'
of the letters are in lowercased.
3 find(sub,start,en Returns the index of the first >>>s2.find("thon",1,7)
d) occurence of a substring in the given 3
string (case-sensitive). If the >>> str.find("ruct",8,13)
substring is not found it returns -1. -1
4 isalnum( ) Returns True if all characters in the >>>s1.isalnum( )
string are alphanumeric (either True
alphabets or numbers). If not, it >>>s2.isalnum( )
returns False. True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in the >>>s1.isalpha( )
string arealphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters in >>>s1.isdigit( )
the string aredigits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters in >>> s1.islower()
the string arelowercase. False True
otherwise. >>> s2.islower()
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True

54
8 isupper( ) Returns True if all the characters in
>>> s1.isupper()
the string areuppercase. False False
otherwise. >>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are only whitespace
>>> " ".isspace()
True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase >>> "HeLlo".lower()
characters. 'hello'
11 upper( ) Converts a string in uppercase >>> "hello".upper()
characters. 'HELLO'
12 lstrip( ) Returns a string after removing >>> str="data structure"
the leading characters. (Left side). >>> str.lstrip('dat')
if used without any argument, it ' structure'
removes theleading whitespaces. >>> str.lstrip('data')'
structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after removing the >>> str.rstrip('eur')
trailingcharacters. (Right side). 'data struct'
if used without any argument, it >>> str.rstrip('rut')
removes thetrailing whitespaces. 'data structure'
>>> str.rstrip('tucers')'data
'
14 split( ) Splits the string from the specified >>> str="Data Structure"
separator and returns a list object >>> str.split( )
with string elements. ['Data', 'Structure']

Exercise Questions: String

1 Mark Questions
Q.No Question Answer
1.
2. What is the output of the following code False

3. What is the output of the following code

print(Strg[ 0: 8 : 2]
4. What is the output of the following?
print('INDIA'.capitalize())
5. Which of the following is not valid string
in Python?
55
6.
be word[: : -2]?

2 Mark Questions
Sr. Question Answer
1. String is immutable data type.So it
does not support item assignment
2. Identify the output of the following Vidya
Python statements.
x="Vidyalaya"
y="Vidya"
if(y in x):
print(y)
3. Look at the code sequence and select the kvsrojAIPUR
correct output
str="KVS RO Jaipur"
for i in str:
if(i.isupper()==True):
print(i.lower(),end="")
if(i.islower()==True):
print(i.upper(), end="")
4. Find the correct output of the following -1
>>>str="The planet earth looks like a
blue marble from outer space"
>>>print(str.find('marble',50))
5. Find the value stored in ctr at the end of 12
this code snippet:
mystr="Darjeeling Tea has a strong
flavour"
ctr=0
for i in mystr:
if i in 'aeiouAEIOU':
ctr += 1
print(ctr)

3 Mark Questions
Sr. Question Answer
1. Write a Python program to input a line of line=input ("Enter a line of text :")
text and a character from user to print ch=input ("Enter a character to
the frequency of the character in the line. search ")
For example k=line.count(ch)
Line entered is : this is a golden pen print ("Frequency is :",k)
The character to search : e
Then output is : Frequency is 2
2. Write a Python Program to input a string s=input("Enter a word :")
to check whether it is a Palindrome string print ("You entered :", s)
or not. (A Palindrome string is that which length=len(s)
is same from both ends like NITIN, rev=""
MALAYALAM, PULLUP) for i in range (-1,-length-1,-1):
rev=rev+s[i]
if s==rev:
print ("Yes, palindrome")
56
else:
print ("Not a palindrome")
3. Using string replication techniques print for a in range(1,4):
the following pattern using any loop. print("hello " * a)
Hello
Hello Hello
Hello Hello Hello

4 Mark Questions
Sr. Question Answer
1. Find Output: Jhu
my_string = 'Jhunjhunu' J@H@U@N@J@H@U@N@U@
print(my_string[:3]) Jhunjhunu
for i in range(len(my_string)): Njh
print(my_string[i].upper(),end="@")
print()
print (my_string)
print (my_string[3:6])
2. Consider the following string mySubject: Computer Science
mySubject = "Computer Science" Scienc
What will be the output of the following Cmue cec
string operations : e
print(mySubject[0:len(mySubject)]) Computer ScienceComputer Science
print(mySubject[-7:-1]) eniSrtpo
print(mySubject[::2])
print(mySubject[len(mySubject)-1])
print(2*mySubject)
print(mySubject[::-2])
3. Consider the following string country: a)Great India
country= "Great India" b)t Indi
What will be the output of the following c)GetIda
string operations(Any Four):- d)a
a) print(country[0:len(country)]) e)Great IndiaGreat India
b) print(country[-7:-1]) f)Great India
c) print(country[::2])
d) print(country[len(country)-1])
e) print(2*country)
f) print(country[:3] + country[3:])

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

57
Lists in Python
List is a standard data type of Python. It is a sequence which can store values of any
kind. In Python, list and dictionary are mutable data types.

For ex -
[ ] Empty list

[1, 2, 3] integers list

[1, 2.5, 5.6, 9] numbers list (integer and float)

Access Items From A List


List items can be accessed using its index position.
List is a sequence like a string.

List also has index of each of its element.

-1) and
one for backward indexing(from -n to -1).

In a list, values can be accessed like string.


Example:
L=[ 10,20,30,40,50,60,70,80,90,100]

0 1 2 3 4 5 6 7 8 9 Forward
Indexing
10 20 30 40 50 60 70 80 90 100
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Backward
Indexing
>>>L[2] Shows : 30
>>>L[-1] Shows : Last element of list i.e. 100.
Traversal of a list :Traversal of a list means to access and process each and every
element of that list. Traversal of a list is very simple with for loop
L=[10,20,30,40,50,60,70,80,90,100]
for i in L :
print(i)

10
20
30
40
50
60
.
.
Operators in List :
A).Concatenation (+ Operator): Python allows us to join two or more lists using

58
Concatenation operator depicted by the symbol +.
Example :
>>> list1 = [1,3,5,7,9]
>>> list2 = [2,4,6,8,10]
>>>list1+list2 # + operator
[1,3,5,7,9,2,4,6,8,10]

B). Repetition/ Replication Operator (* operator): Python allows us to replicate a


list using repetition operator depicted by symbol *.
Example:
>>> s = ['Hello']
>>> s * 4
['Hello', 'Hello', 'Hello', 'Hello']

C). Membership( in / not in operator) : Like strings, the membership operators in


checks if the element is present in the list and returns True, else returns False.
Example:
>>> list1 = ['Red', 'Green', 'Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False

The not in operator returns True if the element is not present in the list, else it returns
False. Example:

>>> list1 = ['Red', 'Green', 'Blue']


>>> 'Cyan' not in list1
True
>>> 'Green' not in list1
False

Slicing : Like strings, the slicing operation can also be applied to lists. List elements
can be accessed in subparts.
>>>list_name[start:stop:step]
Examples:

l=[10,20,30,40,50,60,70,80,90,100]
>>> l[2:6:1]
[30, 40, 50, 60]
>>> l[0:20:2]
[10, 30, 50, 70, 90]
>>> l[-8:-1:1]
[30, 40, 50, 60, 70, 80, 90]
>>> l[ : 6:1]
[10, 20, 30, 40, 50, 60]
>>> l[2 : : 2]
[30, 50, 70, 90]
>>> l[ : : -1]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
>>> l[1:6:-1]
[]
>>> l[ : : 2]
[10, 30, 50, 70, 90]

59
List Methods and Built-in Functions :- Python provides some built-in
functions for list manipulation .
>>>List_name.functionname()
Ex : l=[10,20,30,40,50,60,70,80,90,100]

Function/Method Description Example


Name
len(list) Returns number of elements in >>>len(l)
given list. 10
list(sequence) It converts a sequence into list
format.
List.index(<item>) Returns the index of passed >>> list1 = [10,20,30,20,40,10]
items. >>> list1.index(20)
1
>> list1.index(90)
ValueError: 90 is not in list
List.append(<item>) Appends a single element passed >>> list1 = [10,20,30,40]
as an >>> list1.append(50)
argument at the end of the list >>> list1
The single element can also be a [10, 20, 30, 40, 50]
list >>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]
List.extend(<list>) Append the list (passed in the >>> list1 = [10,20,30]
form of argument) at the end of >>> list2 = [40,50]
list with which function is called. >>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
List.insert(<pos>, Insert the passed element at the >>> list1 = [10,20,30,40,50]
<item>) passed position. >>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
List.pop(<index>) Delete and return the element of >>> list1 = [10,20,30,40,50,60]
passed index. Index passing is >>> list1.pop(3)
optional, if not passed, element 40
from last will be deleted. >>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
List.remove(<value>) It will delete the first occurrence >>> list1 = [10,20,30,40,50,30]
of passed value but does not >>> list1.remove(30)
return the deleted value. >>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x):x
not in list

60
List.clear ( ) It will delete all values of list and >>> list1 = [10,20,30,40,50,30]
gives an empty list. >>> list1.clear()
>>> list1
[]
List.count (<item>) It will count and return number >>> list1 = [10,20,30,10,40,10]
of occurrences of the passed >>> list1.count(10)
element. 3
>>> list1.count(90)
0
List.reverse ( ) It will reverse the list and it does >>> list1 = [34,66,12,89,28,99]
not create a new list. >>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
List.sort ( ) It will sort the list in ascending >>>list1 =
order. To sort the list in ['Tiger','Zebra','Lion',
descending order, we need to 'Cat', 'Elephant' ,'Dog']
write----- list.sort(reverse >>> list1.sort()
=True). >>> list1
['Cat', 'Dog', 'Elephant', 'Lion',
'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]
List.sorted() It takes a list as parameter and >>> list1 = [23,45,11,67,85,56]
creates a >>> list2 = sorted(list1)
new list consisting of the same >>> list1
elements [23, 45, 11, 67, 85, 56]
arranged in sorted order >>> list2
[11, 23, 45, 56, 67, 85]
min() Returns minimum or smallest >>> list1 = [34,12,63,39,92,44]
element >>> min(list1)
of the list 12
max() >>> max(list1)
Returns maximum or largest 92
element of >>> sum(list1)
sum() the list 284

Returns sum of the elements of


the list
Nested Lists
When a list appears as an element of another list, it is called a nested list.
Example :
>>> list1 = [1,2,'a','c',[6,7,8],4,9]
>>> list1[4]
[6, 7, 8]

To access the element of the nested list of list1, we have to specify two indices list1[i][j].
The first index I will take us to the desired nested list and second index j will take us to
the desired element in that nested list.

Some Programs on List


# find the max value in a list
l=[]
61
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
l.append(b)
l.sort()
print("Largest element is:",l[n-1])

Run:
Enter number of elements: 4
Enter element: 10
Enter element: 5
Enter element: 8
Enter element: 9
Largest element is: 10

# find the mean of a list


l=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
l.append(b)
avg=sum(l)/n
print("Average:",avg)

Run:
Enter number of elements: 4
Enter element: 10
Enter element: 5
Enter element: 7
Enter element: 2
Average: 6.0

* Frequency of an element in list


my_list= [101,101,101,101,201,201,201,201]
print("Original List : ",my_list )
n=int(input("enter the element which you want to count:"))
print( my_list.count(n))

Run:
Original List : [101, 101, 101, 101, 201, 201, 201, 201]
enter the element which you want to count: 201
4
Exercise Questions: List Manipulation

1 Mark Questions
Sr. Question Answer
1. Suppose a list is L=[2, 33, "KVS", 14, 25],
what is L[-3]?
2. Find output: 2
List1=[13,18,16,16,13,18]
print(List1.index(16))
3. Given a list L=[1, 2,

What will be the value of L[- 3][1]


62
4. What is the output when we execute

2 Mark Questions
Sr. Question Answer
1. Find the output of the following Python
Code:
>>> L1=[10,20,30] [10, 20, 30, 110]
>>> L2=[110, 220, 330]
>>> L3=L1+L2
>>> L4=L3[0:4] [100, 100, 100, 100]
>>> print (L4)
>>> L4[0]=L4[0]*10
>>> L4[2]=L4[1]*5
>>> L4[1]=L4[2]
>>> L4[3]=L4[3] - 10
>>> print (L4)
2. How the pop( ) function is different from pop() function removes the last
remove( ) function working with list in value and returns the same.
python ? Explain with example. >>>l=[10,20,30,20]
>>>l.pop()
20
The remove() method removes the
first matching value from the list.
>>>l.remove(20)
3. Write a Python program to find and l=["Miao", "Tawang", "Chabua",
display those place names, in which there "Kimin", "Imphal", "Dimapur","Goa"]
are more than 5 characters. for i in l:
For example : if(len(i)>=5):
If the list l= ["Miao", "Tawang", "Chabua", print(i)

The following should get displayed :


Tawang
Chabua
Imphal
Dimapur
4. What is the output when following code N
is executed ?
>>>names = ['Amir', 'Bear', 'Charlton',
'Daman']
>>>print(names[-1][-1])

3 Mark Questions
Sr. Question Answer
1. Write a program that will take a number List1=[10,20,30,40,50,60]
from the key board and find its presence
in the list [10,20,30, 40,50,60]. It will if Num in List1:

else:

2. What is the output when following code is 12


executed ?
names1 = ['Amir', 'Bear', 'Charlton',
'Daman']
names2 = names1
63
names3 = names1[:]
names2[0] = 'Alice'
names3[1] = 'Bob'
sum = 0
for ls in (names1, names2, names3):
if ls[0] == 'Alice':
sum += 1
if ls[1] == 'Bob':
sum += 10
print (sum)
3. Write a program to check if a number is lst = eval(input("Enter first list :-"))
present in the list or not. If the number is num = int(input("Enter the number
present, print the position of the number. which you want to search :-"))
if num in lst :
Print an appropriate message if the
print(lst.index( num ) )
number is not present in the list. else :
print("Number not found")
4. Crate the following lists using a for loop: a)
lst = [ ]
(a). A list consisting of the integers 0 for i in range(50):
through 49. lst = lst + [ i ]
print(lst)
(b). A list consisting the square of the b) lst = [ ]
integer 1 through 50 for i in range(51):
lst = lst + [ i**2 ]
print(lst)
5. Write a program to increment the lst = [ ]
while True :
elements of a list with a number.
num = int(input("Enter a number :"))
lst.append(num)
ch = input("for quit enter y or Y =")
if ch == "Y" or ch=='y':
print(lst)
break

4 Mark Questions
Sr. Question Answer
1. Write a Python program to input 10 L=list()
numbers to store in the list and print the for i in range (10):
third largest number. k=int(input("Enter a number :"))
For example, if the entered numbers in L.append(k)
the list are List are L.sort()
36, 25, 14, - 951, 75, - 85, 654, 88, 9521, print ("List is ", L)
657, then output will be print ("The third largest number is
The third largest number is : 654 :", L[-3])
2. Create the following lists using a for loop: (a)>>>L=list()
(a) A list containing of the integers 0 >>> for i in range (50):
through 49. L.append(i)
>>> print (L)
(b) >>>L=list()
(b) A list containing squares of the >>> for i in range (51):
integers 1 through 50. L.append(i*i)
>>> print(L)
3. Find the output of the following code:
64
>>> L=["These", "are", "a", ["few",
"words"], "that", "we", "will", "use"] [['few', 'words']]
>>> print (L[3:4]) words
>>> print (L[3:4][0][1]) r
>>> print (L[3:4][0][1][2]) False
>>> print ("few" in L) True
>>> print ("few" in L[3]) ['These', 'a', 'that', 'will']
>>> print (L[0::2]) ['that', 'we', 'will', 'use']
>>> print (L[4:]) ['These', 'are', 'a', ['few', 'words'],
>>> print (L) 'that', 'we', 'will', 'use']
4. Find and write the output of the 1
following Python code : [3, 'KVS', 4]
x= [1, 2, [3, "KVS", 4], "KV"] KV
print(x[0]) [1]
print(x[2]) True
print(x[-1]) False
print(x[0:1]) 4
print(2 in x) 7
print(x[0]==8)
print(len(x))
x.extend([12,32,4])
print(len(x))
5. The record of a student (Name, Roll No., (a)>>>sr[3] or >>>sr[-1]
Marks in five subjects and percentage of (b)>>>sr[2][4]
marks) is stored in the following list: (c)>>>max(sr[2])
sr = ['Raman','A-36',[56,98,99,72,69], (d)>>>sr[1]
78.8] (e)>>>sr[
Write Python statements to retrieve the
following information from the list sr.
(a) Percentage of the student
(b) Marks in the fifth subject
(c) Maximum marks of the student
(d) Roll no. of the student
(e) Change the name of the student

65
Tuples in Python
A tuple is a standard data type of Python that can store a sequence of values
belonging to any type.
Tuple is a collection of elements which is ordered and unchangeable
(Immutable). Immutable means you cannot change elements of a tuple in place.
Allows duplicate members.
Consists the values of any type, separated by comma.
Tuples are enclosed within parentheses ( ).
Cannot remove the element from a tuple.
For Example
() empty tuple
( 1, 2, 3) integers tuple
( 1, 2.5, 3.7, 7) numbers tuple
characters tuple
mixed values tuple
string tuple

Creation of Tuple
a) Empty Tuple : >>>T=()
b) Single element tuple: >>>t=(10,)
#Here comma is necessary in single value tuple. Without comma it will be a value, not
a tuple.
c) Long tuple: >>>a=(5,10,15,20,25,30,35,40)
d) Nested Tuple : >>>b=(2,4,6,(8,10),12)
e) tuple() function is used to create a tuple from other sequences.

Example: From String From List


>>>l=[5,10,15,20]
>>>t=tuple(s) >>>p=tuple(l)
>>>t >>>p
(5,10,15,20)

Traversing a Tuple: A tuple can be traverses using loop. Accessing each element.
Example:
>>> a=(2,4,6,8,10) Output: 2
>>> for i in a: 4
print(i) 6
8
10

Accessing Tuples:
Elements of a tuple can be accessed in the same way as a list or string using
indexing and slicing.
T[ i ] returns the item present at index i.
>>>T=(5,10,15,20,25,30,35,40)
>>>T[0] #shows 0 index element
5
>>>T[4] #Fifth element of tuple
25

66
>>>T[-2] #Backward indexing similar to >>>T[6] element
35
>>>T[10] #returns error as index is out of range
IndexError: tuple index out of range

Tuple is Immutable: Tuple is an immutable data type. It means that the elements of a
tuple cannot be changed after it has been created. An attempt to do this would lead to an
error.

>>> t1 = (5,10,15,20,25,30)
>>> t1[2] = 100
TypeError: 'tuple' object does not support item assignment.

Operators in Tuple:
A). Concatenation (+ Operator): Python allows us to join two or more tuples using
Concatenation operator depicted by the symbol +.
Example :
>>> t1 = [1,3,5,7,9]
>>> t2 = [2,4,6,8,10]
>>>t1+t2 # + operator
(1,3,5,7,9,2,4,6,8,10)

B). Repetition/ Replication Operator (* operator): Python allows us to replicate a


tuple using repetition operator depicted by symbol *.
Example :
>>> s = (2,4,6)
>>> s * 3
(2,4,6,2,4,6,2,4,6)

C). Membership( in / not in operator) : Like strings & lists, the membership operators
in checks if the element is present in the tuple and returns True, else returns False.

>>> t1 = ('Red', 'Green', 'Blue')


>>> 'Green' in t1
True
>>> 'Cyan' in t1
False
The not in operator returns True if the element is not present in the tuple, else it
returns False.
>>> 'Cyan' not in t1
True
>>> 'Green' not in t1
False

Slicing : Like strings & lists, the slicing operation can also be applied to tuples. Tuple
elements can be accessed in subparts.
>>>Tuple_name[start:stop:step]
Examples: t=(10,20,30,40,50,60,70,80,90,100)

67
>>> t[2:6:1]
(30, 40, 50, 60)
>>> t[0:20:2]
(10, 30, 50, 70, 90)
>>> t[-8:-1:1]
(30, 40, 50, 60, 70, 80, 90)
>>> t[ : 6:1]
(10, 20, 30, 40, 50, 60)
>>> t[2 : : 2]
(30, 50, 70, 90)
>>> t[ : : -1]
(100, 90, 80, 70, 60, 50, 40, 30, 20, 10)
>>> t[1:6:-1]
()
>>> t[ : : 2]
(10, 30, 50, 70, 90)

Tuple Methods and Built-in Functions :-


Python provides some built-in functions for tuple manipulation .
>>>tuple_name.functionname()

Function/Method Description Example


Name
len(tuple) Returns number of elements in >>> t=(10,20,30,40,50,90,100)
given tuple. >>>len(t)
7
tuple() Creates an empty tuple if no >>> t1 = tuple()
argument >>> t1
is passed ()
>>> t2 = tuple('aeiou')#string
>>> t2
('a', 'e', 'i', 'o', 'u')
Creates a tuple if a sequence is >>> t3 = tuple([1,2,3]) #list
passed as argument >>> t3
(1, 2, 3)
>>> t4 = tuple(range(5))
>>> t4
(0, 1, 2, 3, 4)
count (<item>) It will count and return number of >>> t.count(10)
occurrences of the passed 1
element. >>> t.count(200)
0
index(<item>) Returns the index of the first >>> tuple1 = (10,20,30,40,50)
occurrence of the element in the >>> tuple1.index(30)
given tuple 2
>>> tuple1.index(90)
ValueError: tuple.index(x): x not
in tuple
sorted() Takes elements in the tuple and >>> t1 = (10,100,50,60,30,40)
returns a new sorted list. It should >>> sorted(t1)
68
be noted that, sorted() does not [10, 30, 40, 50, 60, 100]
make
any change to the original tuple
min() Returns minimum or smallest >>> tuple1 =
element of the tuple (19,12,56,18,9,87,34)
>>> min(tuple1)
max() Returns maximum or largest 9
element >>> max(tuple1)
sum() of the tuple 87
>>> sum(tuple1)
Returns sum of the elements of 235
the
Tuple
Nested Tuples : A tuple inside another tuple is called a nested tuple.
In given example information of a student is shown in a tuple form where address part is in
another tuple.

Tuple Comparison: Elements of tuples Tuple unpacking: The way


are compared and returns True/False. by which a tuple can be edited.
>>>t1=(2,3,4) >>>t=(20,40,50,80) #50 to be 60
>>>t2=(2,3,4) >>>a, b, c, d =t
>>>t3=(1,2,3) >>>print(a)
>>>t1 == t2 20
True >>>c= 60 #assigned new value
>>>t1>t2 >>>t=(a,b,c,d) #again packing
False >>>print(t)
>>>t1>t3 (20,40,60,80)
True

Delete a tuple: The del statement is used to delete elements and objects but as you
know that tuples are immutable, which also means that individual element of a tuple
cannot be deleted.
Example:
>> T=(2,4,6,8,10,12,14)
>>> del T[3]
TypeError: 'tuple' object doesn't support item deletion
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
NameError: name 'T' is not defined

Program: the maximum and minimum number from a tuple


t=(10,20,100,50,60,80,90,40)
print(max(t))
print(min(t))
output: 100
10
69
Exercise Questions: Tuple
1 Mark Questions
Sr. Question Answer
1. What will be the output of the following 4
code:

len(Employee)
2. How tuple is different from list? The tuples are immutable sequences
while lists are mutable. The lists can
shrink or grow while tuples cannot.
3. Which of the following creates a tuple?
(a)t1=("a","b") (b) t1[2]=("a","b")
(c) t1=(5)*2 (d) None of the above
4. What is the length of the tuple shown 3
below:

5. What is the difference between (30) When we use type function then (30) is
and (30,)? type of 'int' class where (30,) is a type
of tuple which contain one element.

2 Mark Questions
Sr. Question Answer
1. Write a python program to create tuple=(6,3,1,8,4,9,2,20)
tuple of 10 integer type elements and M=max(tuple)
find the largest element in tuple. print("Largest Value in Tuple: ",M)
2. t1 = (3, 4) (3, 4, '3', '4')
t2 = ('3', '4')
print(t1 + t2)
3. t2 = (4, 5, 6) (6, 7, 4, 5, 6)
t3 = (6, 7) (4, 5, 6, 6, 7)
t4 = t3 + t2
t5 = t2 + t3
print(t4)
print(t5)
4. Discuss the utility and significance of It is a type of arrays . it play very
Tuples, briefly. important role in python . in python it
is immutable type of container which
store any kind of data types it is short
in memory size in comparison of list .
5. Does the slice operator always produce No ,it will print a part of tuple .
a new tuple ?

6. Lists and Tuples are ordered. Lists and Tuples are ordered sequences
Explain. as each element has a fixed position.

70
3 Mark Questions
Sr. Question Answer
1. Find the output of the following Python (10, 20, 30, 40, 50, 60, 70, 20, 30, 50)
Code: 70
t=(10,20,30,40,50,60,70,20,30,50) 2
>>> print (t) 15
>>> print (max(t)) 3
>>> print (t.count(20)) 20
>>> print (t[0]+5)
>>> print (t.index(40))
>>> print (min(t) + len(t))
2. Write a program that inputs two tuples tup1 = eval(input("Enter First tuple :-"))
tup2 = eval(input("Enter second tuple :-"))
and creates a third, that contains all
tup3 = tup1 + tup2
elements of the first followed by all print(tup3)
elements of the second.
3. Create a tuple names as given here: a) names [2 : 5 ]
names = ('jai', 'rahul', 'maya', 'kia', 'Dav',
(b) names [ 0 ]
'Lalit')
Write proper code for getting : (c) names [3 : ]
(a) ('maya', 'kia', 'Dav')
(b) ('jai')
(c) ('kia', 'Dav', 'Lalit')
4. TypeError occurs while statement 2 is Because tuple1 is integer not a tuple. So,
running. Give reason. How can it be we cannot find the length of integer.
If you want to make tuple then you
corrected?
should write ( 5, )
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
4 Mark Questions
Sr. Question Answer
1. What will be stored in variables a, b, c, d, ()
e, f, g, h after following statements? (80, 88, 83, 86)
perc = (88, 85, 80, 88, 83, 86) (88, 85)
(88, 85, 80, 88)
a = perc[2:2]
83
b = perc[2:] (80, 88)
c = perc[:2] ()
d = perc[:-2] (88, 85, 80, 88, 83, 86)
e = perc[-2]
f = perc[2:-2]
g = perc[-2:2]
h = perc[:]

71
2. Write a program to input n numbers tup= ()
from the user. Store these numbers in a while True :
tuple. Print the maximum and minimum n = int(input("Enter a number :- "))
number from this tuple. tup += (n,)
ch = input("To quit enter y/Y =")
if ch == "y" or ch=="Y":
print(tup)
print("Max :-",max( tup ))
print("Min :-",min( tup ))
break
3. Consider the following tuples, tuple1 I. 2
and tuple2 and find the output of the II. 3
following statements: III. (23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
IV. 2
tuple1 = (23,1,45,67,45,9,55,45) V. 67
tuple2 = (100,200) VI. 1
i. print(tuple1.index(45)) VII. 300
ii. print(tuple1.count(45)) VIII. [1, 9, 23, 45, 45, 45, 55, 67]
iii. print(tuple1 + tuple2) IX. (23, 1, 45, 67, 45, 9, 55, 45)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print( sorted ( tuple1 ) )
ix.print(tuple1)
4. Write a program to input names of n def find( name):
students and store them in a tuple. Also, if name in tup :
input a name from the user and find if return name, "is present in ",tup
else :
this student is present in the tuple or not.
return name, "is not present in
",tup
We can accomplish these by:
(a) Writing a user defined function tup = eval( input ("Enter a tuple
(b) Using the built-in function containing name of student :-"))
nam = input("Enter name of student :-")
print( find( nam ) )

72
Dictionary
Dictionaries are used to store data values in key: value pairs. It is a collection which is
ordered*, changeable and do not allow duplicates. Dictionaries are written with curly
brackets, and have keys and value.

Creating the dictionary: -The dictionary can be created by using multiple key-
value pairs enclosed with the curly brackets {}, and each key is separated from its value by
the colon (:)

For example:
# Creating an empty Dictionary
student = { }
print("Empty Dictionary: ")
print(student)
# Creating a Dictionary with dict() method
student = dict({1: 'Mahesh', 2: 'Sunil', 3:'Vikash'})
print(Dict)

Accessing items in a dictionary using keys: -


The elements o f dictionaries are accessed through the keys defined in the key: value
pairs

Syntax:-<dictionary-name>[<key>]
Student ={'Name': 'Manish', 'Age': 15, 'Class': 11,
'Totalmarks':400} student['Name']
Output:- Manish

Accessing Keys or Values:


Student ={'Name': 'Manish', 'Age': 15, 'Class': 11,
'Totalmarks':400} print(Student.keys())
print(Student.values())

Adding and updating dictionary elements


#To update an Item in a Dictionary

Student ={'Name': 'Manish', 'Age': 15, 'Class': 11,


'Totalmarks':400}
Student['age'] = 16
print(Student)
#To add an Item in a Dictionary
Student['Totalmarks'] = '500'
print(Student)
Output:-
73
{'Name': 'Manish', 'age':
{'Name': 'Manish', 'age':
get() method:-
car = {"brand": "Ford","model": "Mustang","year": 1964}
x = car.get("model")
print(x)
Output: Mustang
Traversing a dictionary: - Traversal means accessing individual element
one by one: Student ={'Name': 'Manish', 'age':
for k, v
in
Stud
ent.
Item
s( ):
print
(k, '-
---',
v)
Output: -
Name ---- -Manish
Age - ----16
Class----11
Totalmarks----400
Built-in functions in Dictionary

SN Function Function Details and working


1. len( ) Returns the length of the Dictionary(key-value pair will be count as 1
)
Len(Mydict)
2. dict( ) Creates Dictionary

3. keys( ) Returns all available keys


x.keys()

4. values() Returns all the available values.


x.values( )
output:
5. get( ) The get() method returns the value of the item with the specified key
Mydict ={'Name': 'Raj', 'Age': 15, 'Class': 12,'Totalmarks':450}
print(Mydict.get('Class'))
print(Mydict['Name'])
6. update():- updates the dictionary with the elements from another dictionary
objector from an iterable of key/value pairs
mydict = {'Africa':200,'australia':300,'England':400}
mydict.update({'China':500})
7. del() The del keyword can be used to in-place delete the key that is
present inthe dictionary in Python.
test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21}
74
removes Mani
del test_dict['Mani']
8. pop() method removes the specified item from the dictionary and return
thecorresponding value.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
Mydict.pop('Name')
9. popitem():- The popitem() method removes the item that was last inserted into
thedictionary.
Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
K= Mydict.popitem()
print("Last item of dictionary = ", K)
10. fromkeys() The dict.fromkeys() method creates a new dictionary from the
given iterable (string, list, set, tuple) as keys and with the specified
value.
keys = ('Mumbai','Bangalore','Chicago','New York')
value = 'city'
dictionary = dict.fromkeys(keys, value)
11. copy( ) copy() method returns a copy (shallow copy) of the original
dictionary
original={'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
new = original.copy()
print('Orignal: ', original)

12. setdefault( ) The setdefault() method returns the value of a key (if the key is in
dictionary). If not, it inserts key with a value to the dictionary.
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.setdefault('I')
print("The return value is: ", value)
value = romanNums.setdefault('VI')
print("The return value is: ",value)
print("Updated dictionary: ",romanNums)
13. max( ) & Used to find maximum and minimum respectively fromthe
min( ) dictionary.
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(),
key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(),
key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
14. clear() removes all items from the dictionary.
Mydict ={'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450}
Mydict.clear()
print(Mydict)
15. sorted( ) The sorted() function returns a sorted list of the specified iterable
object
dict = {6:'George' ,2:'John' ,1:'Potter' ,9:'Micheal' ,7:'Robert' ,8:'Gayle' }
b = sorted(dict.keys())
print("Sorted keys",b)
c = sorted(dict.items())
print("Sorted Values",c)
75
Programs on Dictionary:
1. Count the number of times, a character appears in a given string
using a dictionary :

#initializing string
test_str = "AMARDEEP"
# using dict.get() to get count# of each element in string
res = {}
for keys in
test_str:
res[keys] = res.get(keys, 0) + 1
# printing result
print ("Count of all characters in GeeksforGeeksis : \n" , res)

2. Create a dictionary with names of employees, salary and


access them.

Mydict = { }
while True :
name = input("Enter employee name :-")
sl = int(input("Enter employee salary :-"))
Mydict[ name] = sl
user = input("Do you want to quit then enter yes :-")
if user == "yes" :
break;
print(Mydict)
Short Answers type questions[1 mark]

Q1. Keys of dictionary must be


(a) antique (b)unique (c) mutable (d) integers
Q2. We can repeat the values of Key in Dictionary?
a. True
b. False
Q3. Key value concept is in
(a) List (b)String (c)Dictionary (d)Tuple
Q4. What type of error is returned by the following code :
a={'a' : "Apple", 'b' : "Banana" , 'c' : "Cat"}
print(a[1])
Q5. Write the two ways to construct an empty
dictionary.

76
Q6. Write the output of following code:
sales = {'Audi':45, 'BMW':32,
'Ferrari':12}
for x in sales:
print(x)

Q7. Suppose a dictionary days is


declared as:
days={1:"Sun", 2:"Mon",
3:"Wed"}
Write a statement in Python to change Wed to Tue.
Q.8. is used to remove all items form a particular dictionary.
Q.9. What will be
the output:-
d1=

in
d1)
Q10. Which of the following function create a dictionary from sequence of key -
valuePairs.
(a) dictionary( ) (b) dict( ) (c) create( ) (d) convert( )

Short Answer Type Questions [2 marks]


Q1. Parth wants to display the value corresponding to the key in dictionary given
below. As a friend of Parth, help him to find the correct code.
D={1: 2: 3: 4:
(a) print(D.get(3)) (b) print(D[3]) (c) Both of the above (d) None of the above
Q2. Write Python code to convert following two list into one
dictionary :-
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
Q3. Print the value of key from the following dictionary
MyDict = {"class": {"student": {"name": "Mike","marks": {"physics": 70,"history": 80}}}}
Q4. Get the key of a minimum value from the following dictionary

My_dict = {'Physics': 82,'Math': 65,'CS': 75}

77
Q5. Find the output of the following python code:-
a = {}
a[1] = 1
a['1'] = 2
a[1]= a[1]+1
count = 0for i in a:
count += a[i]
print("count=", count)
Q6. What is the output of the
following of code?
a = {i: i*i*i for i in
range(6)}
print (a)
Q7. What will be output of following python program :-
dict = {(3,4,8):4,(5,6,9):3}
print(dict)
print('output:',dict[5,6,])
Q8. Find the output of the following
code:-
dictlang = {'c#': 6, 'GO': 89, 'Python':
4,'Rust':10}cpydict = dictlang.copy()
print(cpydict)
Q9. Find the output of the following code:-
fruitsDict = {'Apple': 100,'Orange': 200,'Banana': 400, 'pomegranate':600 }
if 'Apple' in fruitsDict:
del fruitsDict['Apple']
print('Dict after deleting key =',fruitsDict)
Q10. Create a dictionary of odd numbers between1 and 10, where the key is the
decimal number and the value is the corresponding number in words.

Long Answer Type Question[3 & 4 mark Questions]


1) Answer the following question on the given
dictionary Employee= {'Name': 'Aman', 'Salary':
10000, 'Gender': 'Male'}
(i) Add a new with value in Employee dictionary
(ii) Display all the keys of the Employee dictionary
(iii) Write code to delete all the items of the Employee dictionary
2) What are the differences between dictionary and list?
3) Consider the following dictionary capitals

capitals ={ "Maharashtra": "mumbai","Delhi" : "New Delhi","Uttar pradesh":"Lucknow"}


78
Find the output of the following statements:-
(i) print(capitals.get("Lucknow"))
(ii) print(capitals.keys())
(iii) print("Delhi" in capitals)
4) Write a program to convert a number entered by the user into its
corresponding number in words. for example if the input is 876 then the
Seven
5) Python Program to Multiply All the Items in a Dictionary.
6) Write a Python program to print all unique values in a dictionary.
Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}
7) Write a program to create a dictionary namely Mydict with 10 keys 0 to 9,
each having value as 20. Update the first and last values by adding 100 to
each of them.
8) Write a python function to print sum of all items in a dictionary.

Case Based Questions

1. Mohan is student who is learning python programming. Mohan is unable to find out
the output of the following python program. Help the Mohan by finding outputof the
following :-
Mydict= {'A':10,'B':20,'a':30, 'D':40}
Val_A= ''
for i in Mydict:
if (i>Val_A):
Val_A= i
Val_B= Mydict[i]
print(Val_A) # Line1
print(Val_B) # Line2
print(20 in Mydict) # Line3
print('D' in Mydict)
Mylist.sort() # Line5
print(Mylist[-1]) # Line6

(i) What output does Line1 produce ?


(ii) What output does Line2 produce ?
(iii) (iii)What output does Line3 produce ?
(iv) (iv)What output does Line4 produce ?
79
(v) What is the return value form the list sort() function (line5)
(vi) What output does Line6 produce ?
2. Mr. Rajesh Kumar is a teacher in a school. He is doing his work manually .
As a python learner solve the problems of Rajesh Kumar by python
programs:-
(i) Create a dictionary student which ask Student roll number, Name
and Marksof students and display them in tabular format.
(ii) Display the names of those students who have secured marks more
than 75.
(iii) Delete those students who have secured less than 50 marks

ANSWER KEY

Short Answer Type Questions [1 Marks]


1. B
2. A
3. C
4. KEY ERROR
5. (i) Use of
{} symbol
dict()function
6. Audi
BMW
Ferrari
7.
8. clear()
9. A
10. True
Short Answer Type Questions [2 Marks]
1. D
2. keys = ['Ten', 'Twenty', 'Thirty']values = [10, 20, 30]
res_dict = dict(zip(keys, values))
print(res_dict)
3. print(MyDict['class']['student']['marks']['physics'])
4. print(min(My_dict, key=My_dict.get))
5. count= 4
6. {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
7. {(3, 4, 8): 4, (5, 6, 9): 3}
output: 3
8. {'c#': 6, 'GO': 89, 'Python': 4, 'Rust': 10}
9. Dict after deleting key = {'Orange': 200, 'Banana': 400,'pomegranate': 600}
10. ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
print(ODD)

80
Long Answer type questions
(i) Employee['City']= "Jaipur"
1. print(Employee)
(ii) Employee.keys()
(iii) Employee.clear()
2. 1. List is an ordered set of elements. But, a dictionary is a data structure that is used
for matching one element (Key) with another (Value).
2. The index values can be used to access a particular element. But, in dictionary key
represents index. Remember that, key may be a number of a string. 3. Lists are used to
look up a value whereas a dictionary is used to take one value and look up
another value.
3. (i) None
(ii) dict_keys(['Maharashtra', 'Delhi', 'Uttar pradesh', 'Tamil Nadu '
(iii) True
4. num = input("Enter any number: ") #number is stored as string#numberNames is a
dictionary of digits and corresponding number#names
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch) #converts character to integerrvalue =
numberNames[key]
result = result + ' ' + value print("The number is:",num)
print("The numberNameis:",result)
5. My_dict = {'A':10, 'B':20, 'C':30}
Multiply= 1
for i in My_dict:
Multiply= Multiply*My_dict[i]print(Multiply)
6. L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI":"S005"}, {"VII":"S005"},
{"V":"S009"},{"VIII":"S007"}]
print("Original List: ",L)
u_value = set( val for dic in L for val in dic.values())
print("Unique Values: ",u_value)
7. Mydict= dict.fromkeys(range(10), 20)
Mydict[0]+=20
Mydict[9]+= 20
print(Mydict)
8. # Function to print sum def
ReturnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)

81
return final
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", ReturnSum(dict))
9. def CountFrequency(my_list): # Function definition#
#Creating an empty dictionary
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
print ("% d : % d"%(key, value))

my_list=[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
CountFrequency(my_list) # Function calling
10. D1= { }
i=1
Num= int (input("Enter number of entries: "))
while (i<=Num):
a= input("Enter name: ")
b= input("Enter age:")
D1[a]=b
i= i+1
L= D1.keys()
for i in L:
print(i, '\t', D1[i])
Case Based Question
1. (i) A
(ii) 30
(iii) False
(iv) True
(v) None
(vi) ('a', 30)
2. (i) n=int(input("How many student data you want to enter ..."))
Student={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
Student[roll_no]=[name,marks]
print("{:<10} {:<10} {:<10}".format('Rollno','Name','Marks'))
for k, v in d.items():
name, num = k, v
print(name, marks))
(ii)
n=int(input("Enter n: "))
82
d={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
d[roll_no]=[name,marks]
for k in d:
if(d[k][1]>75):
print(d[k][0])
(iii)
n=int(input("How many student data you want to enter ..."))
Student={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
Student[roll_no]=[name,marks]
for k, v in list(Student.items()):
if v[1] < 50:
del Student[k]
print("Remaining students: ", Student)

83
Introduction to Python Module

A python program consists of three main Component:


1. Library or package
2. Module
3. Function/Sub Modules

RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON

A module is a file containing python definitions, variables and classes and


statementwith .py extension
A Python package is simply a directory of python modules.
A library in python is collection of various packages. Conceptually there is
nodifference between package and python Library.

Advantages of Python Modules

Putting code into modules is useful because of the ability to


import the modulefunctionality.
Reusability: A module can be used in some other python code.
Hence it providesfacility of code reusability
A module allows us to logically organize our python code.
Grouping related code into a module makes the code easier to
understand and use.
Categorization: Similar types of attributes can be placed in a single
module.

Creation of Module:

The following point must be noted before creating a module.

1. A module name should always end with .py extension


2. We will not able to import module if it does not end with .py
3. A module name must not be a Python keyword

A module is simply a python file which contains functions, classes and


variables.
Let us consider the following example of a module name area.py
which contains three functions name area_circle(r), area_square(s),
area_rect(l,b)

import math
def area_circle(r):
return math.pi*r*r
def
area_s
quare
(s):
r
etur
n
s*s
84
def area_rect(l,b):
return l*b
importing Modules: There are two ways to import a module(s) :
1) Using import statement: we can import single as well as multiple modules
i. For importing Single Module
Syntax: import module name
ii. For importing Multiple modules
Syntax: import modulename1, modulename2,

modulename3

To Use function inside module

Syntax modulename.function name

2) Using from Statement: -To import some particular Function(s) from module
we will useimport statement

2.1 To import Particular Function

Syntax: From <module name> import <write name of

Function(s)>OR

From <module name> import *

(This statement will import all the functions from modules)

To use a function inside a module you have to directly call function if you are
importing themodules using from statement.
Example : Let us consider the following code. In this program we import the
module with the help of from statement and directly use the function instead of
specifying Module name.

from
area.py
import
area_rect
area_rect
(5,4)

Importing math module:-In order to use the various constants of


mathematics andoperations, we have to import math module in our program.
Example : import math

Commonly-used constants and functions in math module.

pi: - It is a mathematical constant, the ratio of the circumference of a circle to its


diameter(3.14159...)

For example
>>> print ("The value of pi is :", math.pi)
The value of pi is: 3.141592653589793
85
e: - It is a mathematical constant that returns e raised to the power x, where
e=2.718281.It is the base of natural logarithms. It is also called Euler's number.

For example :
>>>print("The value of e is :", math.e)
The value of e is :2.718281828459045
ceil(x): - Returns the smallest integer that is greater than or
equal to x.For example :
>>>print("ans :",math.ceil(7.3))
Output: ans :8
floor(x): - Returns the largest integer that is less than or equal to x.
>>>math.floor(-45.17)
-46
>>>math.floor (100.12)
100
pow(x,y): - It returns the value of xy, where x and y are numeric expressions.
>>> print ("ans :",
math.pow (3, 3))
Ans :27.0
>>>math.pow (2, 4)
16.0
>>>math.pow (5, 0)
1.0
sqrt(x): - Returns the square root of x.
>>> print ("Squre root of 65=:", math.sqrt (65))

Squre root of 65=:8.06225774829855


>>>math.sqrt (36)
6.0
fabs(x): - Returns the absolute value of x, represented as
math.fabs (x)
where, x can be any numeric value.For example,
>>> print (math.fabs (500.23))
500.23
>>> print (math.fabs (-200))
200
cos(x): - Returns the cosine of x in radians.
>>>math.cos(3)
-0.9899924966004454
86
sin(x): - Returns the sine of x in radians.
>>>math.sin (3)
0.14112000806
tan(x): - Returns the tangent of x in radians.
>>>math.tan (3)
-0.1425465430742778

Random Module: - This module contains functions that are used for
generating random numbers. import statement is the first statement to be given in
a program for generating random numbers:

import random

The various functions associated with this module are as follows: -

(1) random():- It is floating point random number generator between 0.0 to


1.0. Here lower limit is inclusive where as upper limit is less than 1.0. i.e.
0<=N<1 where N is generated random number.

Example: -

>>>import random
>>>n=random.random()
>>>print(n)

0.1738135764235368

(2) randrange():- This method generates an integer between its lower and
upperargument. By default, the lower argument is 0.

Example :-
>>> import random
>>>Number=random.randrange (30)
>>>print(Number)
15

Note: - This line of code shall generate any one random integer number from
0 to 29excluding upper argument.

(3) randint () : - This method generates random integer number. Both the
given rangevalues are inclusive.

Example :-
>>> import random
>>>Number=random.randint (100,500)
>>>print(Number)
151

87
Statistical Module: - This module provides functions for calculating
mathematical staticsof numeric (real valued) data. There are 3 basic functions
under this module.

1. mean()
2. median()
3. mode()

In order to use these functions, we have to import statistics module in our code.

1. mean(): - It calculate the average of all


given numbers.Example: -
>>> import statistics
>>>L=[1,2,3,4,5,6]
>>>print(statistics.mean(L))
3.5 [Note: - 3.5 is the average of all numbers in the list]

median(): - The median is the middle number in a group of numbers. If


group has odd numbers of element then it will return the middle position
value, otherwise will return theaverage of values at mid and mid-1 position.

Example: -
>>> import statistics
>>>L=[10,20,30,40,50,60,70]
>>>print(statistics.median(L))
40

2. mode(): - The mode function returns number that occurs most often within a
set of numbers.

Example:-
>>> import statistics
>>>L=[10,5,30,5,5,60,70]
>>>print(statistics.mode(L))
5

(1 MARK QUESTIONS)

Q1. Which of these definitions correctly describe a module?


a) Denoted by triple quotes for providing the specifications of certain program
elements.
b) Design and implementation of specific functionality to be incorporated into a
program
c) Defines the specifications of how it is to be used.
d) Any program that reuses code.

88
Q2. If a,b,c=3,4,1 then what will be the value of

math.sqrt(b)*a-c

a) 5.0
b) 5
c) 2
d) 4.0
Q3. What is displayed on executing
print(math. fabs(-3.4))?
a) -3.4 b) 3.4 c) 3
d) -3
Q4. What is the file extension of python module file?
Q5. Which of the following is not an advantage of
using modules?
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c)Provides a means of reducing the size of the
program
d) Provides a means of testing individual parts of
the program

Q6. Which operator is used in the python to import all modules from packages?
(a) . operator (b) * operator
(c) symbol (d) , operator

Q7. In python which is the correct method to load a module math?


(a) include math (b) import math
(c) #include<math.h> (d) using math
Q8. Which is the correct command to load just the tempc method from a module
calledusable?
(a) import usable, tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc
Q9. Which of the following can not be returned by random.randrange(4)
a) 0
b) 3
c) 2.3
d) None of the mentioned
Q10. What does random.seed(3) return?
a) True
b) None
89
c) 3
d) 1
(2 MARKS QUESTIONS)
Q1. Write two forms of import statement.
Q2. Write a python program to calculate the square root of given number n.
Q3. What is the utility of Python standard library's math module and random
module?

Q4. Define 'module' and 'package'.


Q5. Which of the following is the same as math.exp(p)? Also give the explanation.
a) e ** p b) math.e ** p
c) p ** e d) p ** math.e
Q6. List any two advantages of modules?
Q7. How is math.ceil (89.7) different from math.floor (89.7)?
(3 MARKS QUESTIONS)

Q1. Select the possible output(s) of the following code from the given option. Also,
specify the maximum and minimum value that can be assigned to variable NUM.
import random
cities =
NUM = random.randint(1,2)+1 for city in cities:
for I in range(1,NUM):
pint(city, \
a) Agra C) Agra
DelhiDelhi Delhi
ChennaiChennaiChennai Chennai
BhopalBhopalBhopalBhopal Bhopal
b) Agra d) ChennaiChennai
Agra BhopalBhopal
DelhiDelhi

Q2.What is the utility of Python standard library's math module, random module and
statistics module?
Q3. Consider the following code:
import math import random
print(str(int(math.pow( random.randint (2,4),2) )), end =
print(str( int ( math.pow(random.randint(2,4), 2))) , end =
print( str ( int (math.pow( random .randint (2,4),2))))
What would be possible outputs out of the
given six choices?
(i) 2 3 4
(ii) 9 4 4
(iii) 16 16 16
(iv) 2 4 9
(v) 4 9 4
(vi) 4 4 4
90
Case Study Based Questions
1. Write a python program that takes a number from 1 to 9 and stored inside
the variable
appears again and the user continues to input another number repetitively
until the guess is correct. On successful guess, the user will get a
and the program will exit.Write a program to perform
insertion sorting on a given list of strings, on the basis of length of strings.
That is, the smallest length string should be the first string in the listand the
largest length string should be the last string in the sorted list.
Answers (1 Mark Questions)
A1 :-b) Design and implementation of specific functionality to be incorporated
into aprogram
A2. :- a) 5.0
A3. :- b) 3.4
A4. The file extension of python module file is .py
A5. Answer: c
A6. * operator.
A7. import math
A8. C) from usable import tempc
A9. C) 2.3
A10. b) None
Answers (2 Marks Questions)

A1. There are two forms of import statements:

1. import <modulename>
2. from <module> import <function>

A2.

import math
n=float(input('Enter n='))
ans=math.sqrt(n)
print('Square root of',n,' = ',ans)
A3.
(i) The math module is used for math related functions that work with all
numberexcept complex numbers.
(ii) The Random module is used for different random number generator
functions.
A4.
Each python program file is a module which imports other modules like
objects and attributes. A python program folder is a package of modules. A
package can have modulesor sub folders.
A5.

Answer: b

EXPLANATION: math.e is the constant defined in the math module.


91
A6. Advantages of modules are:-
1. Reusability : Working with modules makes the code reusable.
2. Simplicity: Module focuses on a small proportion of the problem,
rather than focusing onthe entire problem.

A7.
Ceil: The function 'ceil(x)' in Python returns the smallest integer not less than
x i.e., the next integer on the RHS of the number line. Hence, 'math. ceil(89.7)'
will return 90whereas 'math. floor(89.7)' will return 89.
Answers (3 Marks Questions)

A1. Options b and c are correct. Maximum and Minimum value assigned to NUM
are 3 and2 respectively.
A2.
(i) Math module: The math module is used for math-related
functions that workwith all number types except for complex
numbers.
(ii) Random module: The random module is used for different
random numbergenerator functions.
(iii) Statistics module:- The statistics module is used statistic-related
functions likemean, mode, median etc.
A3. Options ii, iii, v and vi are possible outputs
Answers (Case Study based Questions)
A1.
import random

target_num, guess_num =

random.randint(1, 10), 0while

target_num != guess_num:

guess_num = int(input("Guess a number between 1 and 10 \ until you get it

right:"))print(target_num)

target_num = random.randint(1, 10)

print('Congratulation both target and guess numbers are

same',target_num,guess_num)

print('Well guessed!')

92

You might also like