Class 11 Python Notes
Class 11 Python Notes
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 1
Character Set of Python:
Set of all characters recognised by python. It can be any alphabet, digit or any symbol.
Python uses ASCII character set.
Python Supports the following character set:
Letters: A- Z and a -z
Digits: 0-9
Special Symbols: + , - , /, % , ** , * , [ ], { }, #, $ etc.
White spaces: Blank space, tabs, carriage return, newline, form feed
Other Characters: All ASCII and UNICODE characters.
Tokens:
Tokens are smallest identifiable units.
Different tokens are:
Keywords: reserved words which are having special meaning.
Examples: int, print, input, for, while
Identifiers: name of given by the user to identify variables, functions, constants,
etc.
Literals: literals are constant values. It can be numeric or non-numeric
Operators: triggers an operation. Parameters provided to the operators are called
operands
Examples: + - * % ** / //
Delimiters: Symbols used as separators.
Examples: {} , [ ] ; :
Rules for identifier names:
Keywords and operators are not to be used
Start with an alphabet or an underscore.
Special characters other than underscores are allowed.
Space is not allowed.
Cannot start with a number.
Note: Python is case sensitive and hence uppercase and lowercase are treated
differently.
Example:
o engmark, _abc , mark1, mark2
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 2
The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them. Some are mutable and some are
immutable.
Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 3
Multiple Assignments:
Python allows you to assign a single value to several variables simultaneously.
For example: a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"kvsch“
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Also, it is possible to define and initialize multiple variables with different values as given
below
a, b, c = 5,10,20
The above instruction will create three variables named a,b,c and initialize them with
values 5, 10 20 respectively.
Output Variables:
The Python print statement is often used to output [Link] do not need to be
declared with any particular type. Different type of data can be assigned even after
initializing them with some type of data.
x = 5 # x is of type int
x = "kve " # x is now of type str print(x)
Output: kve
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output of the above code is:
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y print(z)
Output:
Python is awesome
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 4
Expressions:
An expression is a combination of values, variables, and operators.
An expression is evaluated using assignment operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
Operators:
In Python you can implement the following operations using the corresponding operators.
Operators trigger an operation. Some operators need one operand, some need more than
one operand to perform the operation.
Operator Token
addition +
subtraction -
multiplication *
Integer Division /
remainder %
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 5
Binary right shift >>
and &
or \
Check equality ==
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally
two basic statements, the assignment statement and the print statement. Some other
kinds of statements that are if statements, while statements, and for statements generally
called as control flows.
Examples:
An assignment statement creates new variables and gives them values:
>>> x=10
>>> school="kve"
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 6
>>> (10+10)*2 40
Parentheses () overriding the precedence of the arithmetic operators
Example 2:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)
print("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 +(150/5)
print("Value of a + (b * c) /d is", e)
Output:
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) /d is 50.0
Comments:
Comments are discarded by the Python interpreter. Comments acts as some message to
the
Programmer. It can be used as documents.
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:
# this is a single line comment
‘’’ I am a multi line comment’’’
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 7
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more often than not, will encounter
errors. Error caused by not following the proper structure (syntax) of the language is called
syntax error or parsing error.
Import Error: It is raised when you try to import a module which does not exist. This may
happen if you made a typing mistake in the module name or the module doesn't exist in
its standard path. In the example below, a module named "non_existing_module" is being
imported but it doesn't exist, hence an import error exception is raised.
Index Error: An IndexError exception is raised when you refer a sequence which is out of
range. In the example below, the list abc contains only 3 entries, but the 4th index is being
accessed, which will result an IndexError exception.
Type Error: When two unrelated type of objects are combined, TypeErrorexception is
[Link] example below, an int , and a string is added, which will result in TypeError
exception.
Syntax errors: These are the most basic type of error. They arise when the Python parser
is unable to understand a line of code. Syntax errors are almost always fatal, i.e. there is
almost never a way to successfully execute a piece of code containing syntax errors
Run-time error: A run-time error happens when Python understands what you are saying,
but runs into trouble when following your instructions.
Key Error : Python raises a KeyError whenever a dict() object is requested (using
the format a= adict[key]) and the key is not in the dictionary.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 8
Value Error: In Python, a value is the information that is stored within a certain object. To
encounter a ValueError in Python means that is a problem with the content of the object
you tried to assign the value to.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
class. This exception class has to be derived, either directly or indirectly, from
Exception class.
Different types of exceptions:
ArrayIndexOutOfBoundException.
ClassNotFoundException.
FileNotFoundException.
IOException.
InterruptedException.
NoSuchFieldException.
NoSuchMethodException
Modules:
Python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python
code file saved with the extension (.py) is treated as the module. We may have a runnable
code inside the python module. A module in Python provides us the flexibility to organize
the code in a logical way. To use the functionality of one module into another, we must
have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note: In python we have help ()
Enter the name of any module, keyword, or topic to get help on writing Python programs
and using Python modules. To quit this help utility and return to the interpreter, just type
"quit".
Some of the modules like os, date, and calendar so on……
>>> print(sys.version_info)
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 9
sys.version_info(major=3, minor=8, micro=0, release level='final', serial=0)
>>> print([Link](2020))
True
>>> print([Link](2017))
False
Control Structures
Flow of execution means the way in which the instructions are executed. It can be
1. Sequential execution
2. Selection/ Conditional statements
3. Iterations/loop
Sequential execution means executing the statements one by one starting from the first
instruction onwards.
Selection:
Selection or Conditional statements helps us to execute some statements based on
whether the condition is evaluated to True or False.
Use of if statement:
The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.
Syntax:
if <expression>:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 10
Example: Python if Statement
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print(“Finish”)
Output:
3 is greater
done
-1 a is smaller
Finish
a=10
if a>9:
print("A is Greater than 9")
Output:
A is Greater than 9
Alternative if (If-else):
An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
Statement following if.
Syntax of if - else:
if test expression:
Body of if stmts
else:
Body of else
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 11
Flow Chart:
Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
Output:
enter the number 2
a is smaller than the input given
----------------------------------------
a=10 b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")
Output:
B is Greater than A
Chained Conditional: (If-elif-else):
The elif statement allows us to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif
statement is optional. However, unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements following an if.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 12
Syntax of if – elif - else :
If <test expression>:
Body of if stmts
elif < test expression>:
Body of elif stmts
else:
Body of else stmts
Flow Chart:
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 13
enter the number 5
enter the number 9
c is greater
-----------------------------
var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
Output:
3 - Got a true expression value
100
Iteration/Repetition:
A loop statement allows us to execute a statement or group of statements multiple times
as long as the condition is true. Repeated execution of a set of statements with the help
of loops is called iteration.
Loops statements are used when we need to run same code again and again, each time
with a different value.
While loop:
Loops are either infinite or conditional. Python while loop keeps iterating a block of code
defined inside it until the desired condition is met.
The while loop contains a Boolean expression and the code inside the loop is
repeatedly executed as long as the Boolean expression is true.
The statements that are executed inside while can be a single line of code or a block
of multiple statements
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 14
Syntax:
while(expression):
Statement(s)
Flow Chart:
Example Programs:
i=1
while i<=6:
print("KV School")
i=i+1
Output:
KV School
KV School
KV School
KV School
KV School
KV School
_____________________________________________
i=1
while i<=3:
print("KV School",end=" ")
j=1
while j<=1:
print("CS DEPT",end="")
j=j+1
i=i+1
print()
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 15
Output:
KV School CS DEPT
KV School CS DEPT
KV School CS DEPT
For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and
other iterable objects.
Syntax:
for <loopvariable> in <sequence>:
Statement(s)
A sequence or iterable object is used to execute the loop. The for loop executes for a
definite number of times. During each of the iteration, the loop variable holds a value from
the sequence.
Example 1:
L = [ 1, 2, 3, 4, 5]
for var in L:
print( var, end=’ ‘)
output: 0,1,2,3,4,5,6,7,8,9
Example 3:
for k in range(1, 10):
if k% 2 ==0:
print(k, end = ‘ , ‘)
Output: 2, 4, 6, 8
Example 4:
list = ['K','V','S','C','H']
i=1
for item in list:
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 16
print ('School ',i,' is ',item)
i = i+1
Output:
School 1 is K
School 2 is V
School 3 is S
School 4 is C
School 5 is H
Example 5:
#Iterating over a Tuple:
tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)
Output:
These are the first four prime numbers 2
3
5
7
Example 6:
# Iterating over a dictionary:
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
#Iterating over the dictionary to print keys
print ('Keys are:')
for keys in college:
print (keys)
#Iterating over the dictionary to print values
print ('Values are:')
for blocks in [Link]():
print(blocks)
Output:
Keys are:
ces
it
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 17
ece
Values are:
block1
block2
block3
Example 7:
#Iterating over a String:
#declare a string to iterate over
college = 'KVSCH'
#Iterating over the string
for name in college:
print (name)
Output:
K
V
S
C
H
Syntax:
for val in sequence1:
for val in sequence2:
statements
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 18
# Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
Output:
111111
2222
333
44
5
Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays, we
simply use strings. A sequence of any type of characters enclosed within quotes, is a string.
This is how we declare a string. We can use a pair of single or double quotes. Every string
object is of the type ‘str’.
>>> type("name")
<class 'str'>
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 19
>>> name=str()
>>>name
''
>>> a=str('kvsch')
>>> a
' kvsch'
>>> a=str(kvsch)
>>> a[2]
's'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want.
String slices:
A segment or a part of a string is called a slice. Selecting a slice is similar to selecting a
character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.
Slice out substrings, sub lists, sub Tuples using index.
Syntax:
[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
Stop is last index of list
And for step default is 1
For example, 1:
str = 'Hello World!'
print (str) # Prints complete string
print (str[0] )# Prints first character of the string
print (str[2:5] ) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print ( str * 2 )# Prints string two times
print (str + "TEST") # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 20
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
puter
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Note: strings are immutable, which means we can’t change an existing string.
The best we can do is create a new string that is a variation from the original:
‘*’ is called repetition operator and it causes repetition of the characters the specified
number of times.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 21
String functions and methods:
There are many methods to operate on String.
[Link] Method name Description
1. isalnum() Returns true if string has at least 1
character and all characters are
alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1
character and allcharacters are alphabetic
and false otherwise.
3. isdigit() Returns true if string contains only
digits and falseotherwise.
4. islower() Returns true if string has at least 1 cased character and all
casedcharacters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains
only numericcharacters and false
otherwise.
6. isspace() Returns true if string contains only
whitespace characters and false
otherwise.
7. istitle() Returns true if string is properly
“titlecased” andfalse otherwise.
8. isupper() Returns true if string has at least one cased character and
allcased characters are in uppercase
and false otherwise.
9. replace(old,new[, max]) Replaces all occurrences of old in string
with new or at most max occurrences if
max given.
10. split() Splits string according to delimiter str
(space if not provided) and returns list
of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string
inanother string
13. swapcase() Converts lowercase letters in a string to
uppercaseand viceversa
14. startswith(str,beg=0 Determines if string or a substring of string (if starting
, end=len(string)) index beg and ending index end are given) starts with
substring str; returns true if so and false
otherwise.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 22
List:
With the help of lists, we can store different types of items in a variable. It helps us to
store collection of data. List items are ordered, changeable and can be repeated. Indexes
are used to access the items.
Lists are mutable.
Python has a set of built-in methods that you can use on lists
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Whenever we need an array, we can use lists. We can construct / create list in many ways.
Example 1:
list1=[1,2,3,'A','B',7,8,[10,11]]
print(list1)
output:
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
Example 2:
x=list()
print(x)
output:
x []
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 23
Example 3:
Name = “ abcdefg”
L = list(Name)
print(L)
Output:
[ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 24
>>> list1[2:5]
Output: [3, 4, 5]
>>> list1[:6]
Output: [1, 2, 3, 4, 5, 6]
>>>list1 [1:2:4]
Output:[2]
>>> ist1[1:8:2]
output: [2, 4, 6, 8]
List Comprehension:
This is a way to create a new list using an existing list.
Syntax:
NewList = [ expression for variable in iterableobject if condition == True ]
Example1:
list1=[x**2 for x in range(10)]
print(list1)
output:
[ 0,1,4,9,16,25,36,49,64,81]
Note: in the above given code, a new list named list1 is created using the expression x**2,
where the for loop is used to assign different values to ‘x’ using the range( ) function.
Example 2:
x=[z**2 for z in range(10) if z>4]
print(x)
Output: [25, 36, 49, 64, 81]
Example 3:
x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
print(x)
Output: [1, 9, 25, 49, 81]
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are created by
enclosing items within round brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 25
Tuples are more efficient than list due to python’s implementation.
We can create tuple in different ways.
X=( ) # an empty tuple
X=(1,2,3) # a tuple with three elements
X=tuple(list1)
X=1,2,3,4
Syntax:
<Name of the tuple>[index]
Example:
T = ( 1, 2,4,6)
print(T[0])
Output: 1
print(T[--1])
Output: 6
index (): Searches the tuple for a specified value and returns its position in the tuple.
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
Output: 1
(Or)
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 26
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=[Link](2)
>>> print(y)
Output: 1
len(): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
output: 12
Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator" object
that we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710>. The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator is that you can
iterate over it, but ONLY ONCE.
Example:
>>> x = (i for i in 'abc')
>>> for i in x:
print(i)
Output:
a
b
c
Example:
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 27
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
Set comprehension:
Similarly, to list comprehensions, set comprehensions are also supported by Python:
Example:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
Output:
{'r', 'd'}
Output:
{24, 18, 27, 21}
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are created with curly brackets, and they have keys and values. It is a
mapping. Values can be of any type. Only immutable types are allowed as keys. It is not
possible to repeat keys. They are to be unique.
Key-value pairs
Unordered
Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 28
Functions available for handling dictionary:
Method Description
Remove the item with key and return its value or d ifkey is not
pop(key[,d])
found. If d is not provided and key is not found, raises KeyError.
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions
Syntax:
<dictionary> = { expression for <variable> in sequence }
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 29
Example:
>>> z={x: x**2 for x in (2,4,6)}
>>> z
{2: 4, 4: 16, 6: 36}
>>> dict11 = {x: x*x for x in range(6)}
>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 30
Multiple Choice Questions
1. Which of the following is not a keyword?
a) Eval b) assert c) nonlocal d) pass
2. What is the order of precedence in python?
(i) Parentheses ii) Exponential iii) Multiplication iv) Division v) Addition vi)
Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
3. What error occurs when you execute the following Python code snippet?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError
a) 30.0
b) 30.8
c) 28.4
d) 27.2
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 31
a. print(‘hello’, ‘how’, ‘are’, ‘you’)
b. print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c. print(‘hello-‘ + ‘how-are-you’)
d. print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
[Link] of the following method is used to delete element from the list?
a)del()
b)delete()
c)pop()
d)All of these
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 32
b. indicates the end of the sequence
c. indicates the difference between every two consecutive numbers in the sequence
d. generates numbers up to a specified value
Answers of MCQ:
1) A 2)A 3)B 4)A 5)D 6)C 7)A 8)B 9) D 10)B 11)B 12)B 13)A 14)C
15)C
Sum = 0
for k in range(5):
Sum = Sum+k
print(Sum)
Sum = 0
for k in range(10 , 1, -2):
Sum = Sum+k
print(Sum)
for k in range(4):
for j in range(k):
print(‘*’, end = ‘ ‘)
print()
5. How many times the following loop will execute? Justify your answer
A=0
while True:
print(A)
A =A+1
6. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 33
print(A, ‘ , ‘)
A =A+1
7. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
print(‘\n’, A)
T = (5)
T = T*2
print(T)
10. What kind of error message will be generated if the following code is executed
A=5
B = ‘hi’
d = A+B
print(D)
S = ‘abcdefgh’
L = list(S)
print(L[1:4])
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 34
print( y)
1)10
2)30
3)
*
* *
* * *
4) * * * * *
* ***
* * *
* *
*
5)infinite loop. Condition / test expression is always Ture.
6) 0,1,2,3,4,5,6,7,8,9
7) 0,1,2,3,4,5,6,7,8,9
10
10)TypeError
11) [1,2,3,4,5,6,7,8,9]
12) [1,2,3,4,5,6,7,8]
14) 1
1
[Link] Python code to remove an element as entered by the user form the list, L
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 35
[Link] a list k, by selecting all the od numbers within the given range, m and n. User
will input the values of m , n at run time
[Link] Python code to create and add items to a dictionary. Ask the user to input key
value pairs. Continue as long as the user wishes.
[Link] Python code to find whether the given item is present in the given list using for
loop.
[Link] a list, L, with the squares of numbers from 0 to 10
[Link]. Rahul wants created a dictionary to store the details of his students and to
manipulate thedata.
He wrote a code in Python, help him to complete the code:
3) m = int(input(‘lower limit’))
n = int(input(‘upper limit’))
n = n+1
L = [x for x in range(m, n) if x%2!=0]
4)
D={}
while Ture:
K = input(‘type a key’)
V = int(input(‘type the value’)
D[K] = V
C = input(‘type ‘y’ to add more’)
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 36
if C!=’y’:
break
5) flag = 0
L = eval(input(‘input a list on numbers’))
E = int(input(‘item to be searched’)
K =len(L)
for p in range(K):
if E ==L(p):
flag = 1
print(‘found and index is ‘,p)
if flag==0:
print(‘not found’)
6)
list1=[]
for x in range(10):
[Link](x**2)
list1
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
OR
list1=list(map(lambda x:x**2, range(10)))
7)
Statement 1 : StudentDict = dict( )
Statement 2 = for i in range( n ):
Statement 3: studentDict[rollno]=[name, physicsMarks, chemistryMarks, mathMarks]
KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 37