Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Modern

OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

CHAPTER- 1
PYTHON REVISION TOUR

INTRODUCTION TO PYTHON

 Python is a Python is a popular high-level programming language developed by Guido Van


Rossum in February 1991 and got its name from a BBC comedy series “Monty Python’s Flying
Circus”.
 It is a general-purpose language, used to create a range of applications, including data science,
software and web development, automation, and improving the ease of everyday tasks.
 It is an interpreted and platform independent language i.e. the same code can run on any
operating system.
 It can be used to follow both procedural and object-oriented approaches to programming.
 It is an open Source programming language, hence free to use.

 It is based on two programming languages: ABC language and Modula-3.

LANGUAGE BASICS OF PYTHON

Like natural languages, programming languages have their own character sets and grammar rules (syntax
or semantics).
Python CharacterSet : Set of valid characters that a language can recognize. A character represents any
letter, digit or any other symbol. Python has the following character sets: ·
Letters A-Z, a-z
Digits 0-9
Special symbols SPACE + - * / \ ( ) * + , - = !>< ‘ “ ; .: % # ^ |,
Whitespaces Blank space, tabs, newline, formfeed
Other Characters All ASCII and Unicode

Token / Lexical Unit: The smallest individual unit in a python program is known as Token or Lexical Unit. A
token has a specific meaning for a python interpreter.

Note: In English a sentence is formed with noun, verb, adverb, adjective, preposition etc. by following
grammatical rule, similarly in programming language, a statement is formed with tokens that includes
Keywords, Identifiers, Literals, Operators and Punctuators.

Keywords: Keywords are the reserved words and have special meaning for Python Interpreters. Each
keyword can be used only for that purpose which it has been assigned. Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. As Python is case
sensitive, keywords must be written exactly as given in Table given below.

assert and as break class continue def del else


elif except finally from False for global is in
if import lambda nonlocal not None or pass raise
return True try with while yield

Identifiers: These are the names given to variables, objects, classes or functions etc. there are some
predefined rules for forming identifiers which should be followed else the program will raise Syntax Error.

Std. - XII (Science) 178 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
The rules for naming an identifier in Python are as follows:

 The name must begin with an alphabet (uppercase or a lowercase) or an underscore sign (_).
 Remaining characters may be followed by any combination of characters a-z, A-Z, 0-9 or underscore (_).
 It can be of any length. (However, it is preferred to keep it short and meaningful).
 It should not be a keyword or reserved word as given above in the Table
 It cannot use space or other symbols other than _ .
 Python is case sensitive language. Hence uppercase and lowercase with same name are considered as
different identifiers.

Example of valid Identifiers are

Myfile data_90 length _tractNo File90

Example of invalid Identifiers are

Record-file 2023_budget break My%file that loan

Literals: The data items that have a fixed value are called Literals.

1. Number: Number data type stores numerical values only. It is further classified into three different types: int,
float and complex.
i. Int : are whole numbers (+ve or –ve) without any fractional part. Integer numbers can be represent in 4
different ways.
a. Decimal : whole number without any prefix. E.g. 89 ,25
b. Binary : numbers formed with 0’s and 1s prefixed with 0b. e.g. 0b1010
c. Octal : numbers formed with digit 0- 7 prefixed with 0o. e.g. 0b651
d. Hexa-decimal: numbers formed with digit 0 – 9, a-f prefixed with 0x. e.g. 0x1E
ii. Floating point Number: any number having fractional parts. Floating point numbers can be represent in
2 different ways.
a. Fixed-point/Standard notation: fractional part separated with a . (dot) e.g. 0.67
b. Scientific Notation /Exponent Notation: represented with mantissa and exponent. E.g. 3e5 where 3 is the
mantissa and 5 is exponent. Here the value is calculated as 3X105.

Note: value with , (comma) , decimal integer with leading 0 are invalid numbers. E.g. 23,000, 098

iii. Complex : a complex number is a number of the form A+Bi where i is the imagionary number, equal to
the square root of -1. Python refers to A+Bj. For ex.A= 1.5+2.6j

2. Boolean: Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two
constants, True and False. Boolean True value is non-zero. Boolean False is the value zero.
3. String: A stringis a set of characters (letter, symbols and digits) enclosed within ‘’(single) or “” (double) or ‘’’’’’
(triple) quotes. For ex.

X=”this is my pen”

4. Special Literal

Python has one special literal, None which indicates the absence of a value.

5. List
a sequence of values enclosed within [ ]. For ex. X=[3,5,2,8,34,7]
6. Tuple
a sequence of values enclosed within (). For ex. X= (5,7,4,6,4,6)

Std. - XII (Science) 179 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
7. Dictionary
it is a mapping object. With key: value pair. For ex x=,1:’red’,’2:’green’,3:’blue’-

Operators: These are the symbols that perform specific operations on some variables. Operators operate
on operands. Some operators require two operands and some require only one operand to operate.
Operator is a symbol or combination of symbols that perform a computational operation on one or more operands.
Operands are values or variables on which operator performs an operation. An operator is used to perform specific
mathematical or logical operation on values.

Types of operators

i. Based on number of operands


a. Unary ( works on 1 operands) e.g. -5 Unary operator includes ( + ,- , ~ , not)
b. Binary (works on 2 operands) e.g. 3+6 others are binary operator

ii. Based on operation it performs

Arithmetic operators

Operator Description Example


+ Performs addition X= 10+3  13
- Performs subtraction X= 10-3  7
* Performs multiplication X= 10*3  30
/ Performs division and return the quotient X= 10/3  3.333
// Performs floor division and return the quotient X= 10//3  3
% Performs division and return the reminder X= 10%3  1
** Performs exponentiation X= 10**3  1000
Assignment operators

Operator Description Example


= Performs an assign X= 10
+= Performs addition and assign X +=1 same as X=X+1
-= Performs subtraction and assign X -= 1
*= Performs multiplication and assign X*= 1
/= Performs division and assign X /= 1
//= Performs floor division and assign X //= 1
%= Performs division and assign X %= 1
**= Performs exponentiation and assign X **= 1
Relational/ Comparison operators

< Less than Returns True if the first operand is less than the second; otherwise
False.
> Greater than Returns True if the first operand is greater than the second;
otherwise False.
<= Less than equals Returns True if the first operand is less than or equals to the
second; otherwise False.
>= Greater than equals Returns True if the first operand is greater than or equals to the
second; otherwise False
== Equals to Returns True if both operands are equal; otherwise False
!= Not equals to Returns True if both operands are not equals;otherwise False

Example :

10<5 Output : False 10>=10 Output: True

Std. - XII (Science) 180 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
50 > 9 Output : True 50 != 9 Output: True
50<=50 Output : True 50==50 Output: True

Logical operators

and Returns True, if both expression have True value ; otherwise False.
or Returns True, if any one or both expression have True value ; otherwise False.
not Returns True, if the operand has False value; otherwise False. It is a unary operator

The Or on Relational expression

The or evaluates to True if either of its operands evaluates to True; False if both operands evaluate to False.

Example

3>=2 or 3<2 returns True 3>=2 or 3>1 returns True

The Or on Number, string or list as operands

In an expression x or y, if the first operand has false, then return second operand y as result, otherwise return x.

Example

0 or 0 returns 0 ‘b’ or ‘a’ returns ‘b’


0 or 8 returns 8 ‘’ or ‘a’ returns ‘a’
5 or 0 returns 5 ‘’ or ‘’ returns ‘’

The and operator on Relational expression as operands

The and evaluates to True if both of its operands evaluates to True; False if any one operand evaluate to False.

Example

3>=2 and 3<2 returns False 3>=2 and 3<50 returns True

The and operator on Number, string or list as operands

In an expression x or y, if the first operand has false, then return first operand x as result, otherwise return y.

Example

0 and 0 returns 0 ‘b’ and ‘a’ returns ‘a’


0 and 8 returns 0 ‘’ and ‘a’ returns ‘’
5 and 0.0 returns 0.0 ‘’ and ‘’ returns ‘’

The Not operator:

Works on single operand(unary operator). Negates the value in an expression. For example.

Example

not 0 returns True not -34 returns False


not 8 returns False not 5>100 returns True
not 50>5 returns False
Chaining of comparison operators
Std. - XII (Science) 181 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
Python allow to chain multiple comparison operators like shortened. For example rather than writing 1<2 and 2<3
one can write 1<2<3. Similarly 11<13>12 is the shortened version of 11<13 and 13>12.

Bitwise operators

& (and) Returns 1 if both bits are 1; otherwise 0


| (or) Returns 1 if any one or both bits are 1; otherwise 0
^ (xor) Returns 1 if either of the bits are 1 and 0 if both are 0 or 1.
~ (compliment) Invert all bits of the operand
<< (shift left) Shift (n) bits towards left
>> (shift right) Shift (n) bits towards right
Example :

X=7 5  111 X=7 5  111


Y=3 3 011 Y=3 3 011
Z=X & Y 011 (and) Z=X | Y 111 (or)
print(Z) Output : 3 print(Z) Output : 7

Identity operator

is Returns True, if both variables point to the same memory location.


is not Returns True if both variables are not pointing to the same memory location.
Example :

X=5 Output : True X=5 Output : False


Y=5 Y=5
Z=X is Y Z=X is not Y
print(Z) print(Z)

Membership operator

in Returns True, when an item is a part of Sequence/collection; Otherwise False


not in Returns True, when an item is not a part of Sequence/collection; Otherwise False.
Example :

‘f’ in ‘football’ Output : True 78 not in[4,66,12] Output : True


‘g’ in ‘football’ Output : False ‘g’ not in ‘football’ Output : True

NOTE: When we compare two variables pointing to same value, then both Equality (==) and identity
(is) will return True. But when same value is assigned to different objects, then == operator will return
True and is operator will return False.
Punctuators: These are the symbols that are used to organize sentence structure in programming
languages. Common punctuators are: ‘ ‘’ # $ @ *+ ,- = : ; () , .
Comment: Commentsare non-executable statements used to provide additional readable information about the
logic. A comment begins with # (hash) sign. Python supports both single line and multi-line comments.

 Single-line comment can be started with # sign


 Multi-line comment can be given with docstrings (triple quote)

Variables: In Python, variables are not storage containers like other programming languages. These are
the temporary memory locations used to store values which will be used in the program further. Each
time we assign a new value to a variable it will point to a new memory location where the assigned

Std. - XII (Science) 182 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
value is stored. In Python we do not specify the size and type of variable, besides these are decided as
per the value we assign to that variable.
Variable can be defined using assignment as follows.

X=45

Declaring multiple variables

Assigning same value to multiple variables

One can define multiple variable at the same time as follows:

a=b=c=90

Assigning multiple value to multiple variables

a,b,c=10,20,30

Note: expression separated with commas are evaluated from left to right and assigned in same order. For ex.

x,x=20,30
y,y=x+10,x+20
print(x,y)  30 50

Note : Python supports dynamic typing. That is when a variable is assigned with a value the variable refers to that
data type. For ex.

X=90

Y=12.8

Where x is of int type, y is of float. You can check using type(x) method

Data Type: It specifies the type of data we will store in the variable according to which memory will be
allocated to that variable and it will also specify the type of operations that can be performed on that
variable. Examples: integer, string, float, list etc.
Dynamic Typing: It means that it will be decided at the run time that which type of value the variable
will store. It is also called implicit conversion. For example,

A=90 # integer type


B=A+40.5 # floating point type
A=”OXFORD” # string type

Here, we need not to specify the type of value a will store besides we can assign any type of value to a
directly. Similarly, the data type of B will be decided at run time.

Evaluation of Expression

An expression may be Arithmetic , Relational ,logical , string etc.

While evaluating an arithmetic expression, Python follows the Precedence (priority) of operators as well as
associativity of operators as follow.

Precedence of Operators

 PEDMAS (Parenthesis Exponentiation Division Multiplication Addition and Subtraction)


 Division and multiplication which is earlier
 Addition and subtraction which is earlier.
Std. - XII (Science) 183 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
When an expression contains more than one operator from different levels, their precedence (order or hierarchy)
determines which operator should be applied first. Higher precedence operator is evaluated before the lower
precedence operator. In the following example, '*' and '/' have higher precedence than '+' and '-'.

Note: a) Parenthesis can be used to override the precedence of operators. The expression within () is evaluated first.
b) For operators with equal precedence, the expression is evaluated from left to right.

Operator Priority
() Highest
**
~
+, - (Unary)
* , / , //, %
+ ,- (Binary)
&
^
|
<, <= > ,>= ,!= ,==
Is , is not
not
and
Lowest
or

Associativity

 When an expression contains operators from different levels, the precedence of operators applied.
 When an expression contains operators from single level, the associativity of operators applied.
 Almost all operator have Left to Right Associativity except Exponentiation (**) which has Right to Left
Associativity.

Example #1

X= 5-3*2
here, operators from different levels, the precedence of operators applied. Hence * (multiplication ) shall be
performed at first followed by –( subtraction). Output : -1

Example #2

X= 15-5+2
here, operators from same level, the associativity of operators applied. Hence - (subtraction ) shall be performed at
first followed by + ( addition) according to L-R.

Type Conversion

While evaluating an expression, value of one type is changed to another type. This process is known as conversion.
Conversion are of 2 types.

 Implicit: conversion performed automatically by the interpreter.


 Explicit : programmer define conversion forcefully to a specific type known as type casting.

Implicit conversion (coercion) generally applied whenever different data types (compatible) are applied in an
expression so as not to lose any value. In this case, value is converted to largest type (type promotion). For example

5+90  95 (int + intint)


5+90.5  95.5 (int + float  float)
90.5+ 8.5+3.5j(99+3.5j) ( float+ complex  complex)
Std. - XII (Science) 184 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

Note. In python, the / (division) always produces floating point, even if both operands are of integer.

Explicit conversion: generally applied when a type demoted or incompatible type is converted. Type casting is
performed by:

<datatype> (expression)

Data type Description Example


int() Convert number / string with number / Boolean A=int(‘23’) 23
into integer A=int(4.5) 4
float() Convert number / string with number/ Boolean A=float(True) 1.0
into float A=float(45) 45.0
complex() Convert number into complex A=complex(2) (2+0j)
str() Number /Boolean to String A=str(54) “54”
A=str(0o23) 19
bool() Any type to Boolean A=bool(-23) True
A=bool(’a’)  True
A=bool(‘’) False
A=bool(0)  False

DATA TYPES IN PYTHON:

Above data types are classified in two basic categories: Mutable data types and Immutable data types.
Mutable data types are those data types whose value can be
changed without creating a new object. It means
mutable data types hold a specific
memory location and changes are made
directly to that memory location. Immutable
data types are those data types whose value cannot be
changed after they are created. It means
that if we make any change in the
immutable data object then it will be assigned a new
memory location.

1. In Numeric data types, Integers allow storing whole numbers only which can be positive
or negative. Floating point numbers are used for storing numbers having fractional parts like
temperature, area etc. In Python, Floating point numbers represent double precision i.e. 15-
digit precision. Complex numbers are stored in python in the form of A + Bj where A is the real
part and B is the imaginary part of complex numbers.

2. Dictionary is an unordered set of comma separated values where each value is a


key:value pair. We represent the dictionary using curly brackets {}. Keys in the dictionary
should be unique and they cannot be changed while values of the keys can be changed.

3. Boolean allows to store only two values True and False where True means 1 and False
means 0 internally.

Std. - XII (Science) 185 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
4. Sequence data types store a collection or set of values in an ordered manner. We can
traverse the values/elements using indexing. The sequence data types are:

In our daily life, we deal with textual or numeric data. Textual data are generally known as string. A
string is a sequence of characters that includes alphabet, digits, symbols or non-printable characters
enclosed within single quote(„‟), double quote(“ ”) or triple quote (single quote or double quote 3
times).
Declaration of a string
x= “” # creates an empty string
x=”good morning” #a string with characters
x=”345” # a string with digits (x has no numeric values)
x=str() # create an empty string
Declaration of a multi-line string
Stringcan be extended to multiple lines as follows.
Y=”good \ # multiline string
morning”
Z= '''good # multiline string
Morning '''

Escape Sequences
A string may contain escape sequence characters such as \n\b including Unicode. Escape sequences
are non-graphic characters that can be typed directly from keyboard (no character is typed when
these key are pressed). An escape sequence is represented by a backslash (\) followed by one or
more characters. The following table gives list of escape sequences.
Character Description Character Description
\\ Backslash \r Carriage return
\‟ Single quote \t Horizontal tab
\” Double quote \uxxxx 16bit hex Unicode
\a Alert (bell) \Uxxxxxxxx 32bit Hex Unicode
\b Backspace \v Vertical tab
\f Formfeed \ooo Octal value
\n New line \xhh Hexa-decimal value.
Example
Code
X=‟this is a \nsample line‟
Output: (in 2 lines)
this is a
sample line
Internal representation of string
The sequence objects in python includes string, tuple, or list in which elements/items are stored in
consecutively and can be accessed using index or position.
For example suppose you declare a string as
x=”GOOD MORNING”
Std. - XII (Science) 186 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

the string object x is stored internally as:


Seq. Value G O O D M O R N I N G
Forward index 0 1 2 3 4 5 6 7 8 9 10 11
Backward index -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Accessing an element from sequence

You can access a single item from sequence with the corresponding integer indices. Indices in
Python are zero-based. This means the index 0 corresponds to the first (leftmost) item of a
sequence, 1 to the second item, and so on.
Ex.
print(x[0]) output : G
print(x[3]) output : D
Python also support to access elements backward with first index as -1 (rightmost) as follows.
Ex.
print(x[-5]) output : M
print(x[-9]) output : D

Note: Accessing an element outside the length of a sequence raises IndexError: index out of range
Accessing element by elements using iteration (collection)
for I in x:
print(I)
Accessing element by elements using iteration (index)
for I in range(len(x)):
print(x[I])
Accessing elements in reverse order
for I in range(-1,(-len(x)-1),-1):
print(x[i])

String is an Immutable object in python.

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

str1 = "Hello World!"


str1[1] = 'a' #if we try to replace character 'e' with 'a'
TypeError: 'str' object does not support itemassignment

Accessing part of a sequence

Std. - XII (Science) 187 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists.
You can also use them to modify or delete the items of mutable sequences such as lists.
Slicing is similar to indexing but returns a sequence of items instead of a single item. The indices
used for slicing are also zero-based.

The syntax

obj[start:stop:step]

Parameters

 start (optional) - Starting integer where the slicing of the object starts. Default to 0, if not
provided.
 Stop(optional) - Integer until which the slicing takes place. Default to -1 (last element).
 step (optional) - Integer value which determines the increment between each index for
slicing. Defaults to 1 if not provided.

For example

print(x[::]) output: GOOD MORNING


print(x[:4]) output: GOOD
print(x[4:]) output: MORNING
print(x[::-1]) output: GNINRMO DOOG
print(x[-7:-4]) output: MOR

Note: You can specify index in slices out of range, but it does not raise any error.

print(x[-2:7]) output :
print(x[-2:7:-1]) output : NIN
print(x[2:-3]) output : OD MORN
print(x[-2:-3]) output:
print(x[-2:-1]) output N
print(x[-100:-1]) output GOOD MORNIN
print(x[2:100]) output: OD MORNING

Operators on String

String manipulation is one of those activities in programming that programmersdo all the time.
Operator Syntax Example
+ (concatenation) String1+string2 “abc+”xyz” returns “abcxyz”
* ( replication) String1* number “abc”*2 returns “abcabc”
Number * string 2*”abc” returns “abcabc”
“abc”*”2” returns error
in subString in string “foot” in “football” returns True
“abc” in “football” returns False
not in subString not in “foot” not in “football” returns False
string “abc” not in “football” returns True
<, > ,<= ,>= ,= String1 < string2 “abc” > “ABC” returns True
Std. - XII (Science) 188 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

=,!=

String Functions
In many programming languages, you have to write a lot of hard code to manipulate strings. In
Python, on the other hand, you have several built-in functions in the standard library to help you
manipulate strings in many different ways.
Function Description Example
len() Returns length of a string len(“abc”) returns 3
ord() Returns the ordinal value ord(„A‟) returns 65
chr() Returns character chr(65) returns „A‟

STRING FUNCTIONS:

len (string) It returns the number of characters in any string including spaces.
capitalize() It is used to convert the first letter of sentences in capital letter.
title() It is used to convert first letter of every word in string in capital letters.
upper() It is used to convert the entire string in capital case letters.
lower() It is used to convert entire string in small case letters.
count(substring, It is used to find the number of occurrences of substring in a string.
[start], [end]) We can also specify starting and ending index to specify a range for
searching substring.
find(substring, This function returns the starting index position of substring in the
[start],[end]) given string. Like count(), we can specify the range for searching using
starting and ending index. It returns -1 if substring not found.
index(substring) It returns the starting index position of substring. If substring not
found then it will return an error “Substring not found”.
isalnum() It is used to check if all the elements in the string are alphanumeric or
not. It returns either True or False.
islower() It returns True if all the elements in string are in lower case, otherwise
returns False.
isupper() It returns True if all the elements in string are in upper case, otherwise
returns False.
isspace() It returns True if all the elements in string are spaces, otherwise
returns False.
isalpha() It returns True if all the elements in string are alphabets, otherwise
returns False.
isdigit() It returns True if all the elements in string are digits, otherwise returns
False.
split([sep]) This function is used to split the string based on delimiter/separator
value which is space by default. It returns a list of n elements where
the value of n is based on delimiter. The delimiter is not included in
the output.
Std. - XII (Science) 189 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

partition(sep) It divides the string in three parts: head, separator and tail, based on
the sep value which acts as a delimiter in this function. It will always
return a tuple of 3 elements. The delimiter/separator will be included
as 2nd element of tuple in the output.
replace(old, It is used to replace old substring inside the string with a new value.
new)
strip([chars]) It returns a copy of string after removing leading and trailing white
spaces by default. We can also provide chars value if we want to
remove characters instead of spaces. If chars is given then all possible
combination of given characters will be checked and removed.
lstrip([chars]) It returns a copy of string after removing leading white spaces. If chars
value is given then characters will be removed.
rstrip([chars]) It returns a copy of string after removing trailing white spaces. If chars
value is given then characters will be removed.

A variable can be scalar or collection/Iterative. A variable is said to be scalar if it is capable of storing only
one value at a given instance of time. For ex.
X=20 # value of X is 20 now
X=50 # value of X is 50 now
X= X+10 # value of X is 60 now
Where as a variable is said to be collection/iterative, if it is capable of storing many value at a given instance
of time. For ex.
X=[2,5,20,7,8] # X contains 2, 5,20,7 and 8.
In Python, a list is a collection/sequence of values of different types enclosed within Square brackets [ ].
e.g. x=[90,33,656,44,66,”abcd”,99.00,True]
Creating / declaring a list
1. Creating list
 X= [] #creates empty list
 Y=list() #creates empty list
 X=[3,7,1,34,70] # creates list of integers
 Y=[„book‟,‟pencil‟] #creates list of strings
 Z=[67,‟pencil‟,87.90] #creates list of mixed types
 X1=list(„good‟) #creates list of string with individual characters e.g. [„g‟,‟o‟,‟o‟,‟d‟]
 Y1=list((1,2,3,4))
 X2=list(input(“Enter list elements”))
 Z1= eval(input(“Enter list elements”)
Internal representation of a List
Like string, a list is also collection/Sequence having all elements with index position as given below.
1. A list object like y=[3,6,8,13,5,6,33,20,56,90,15,23] stored internally as:
Seq. Value 3 6 8 13 5 6 33 20 56 90 15 23
Forward index 0 1 2 3 4 5 6 7 8 9 10 11
Backward index -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Accessing elements of a list
Std. - XII (Science) 190 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
As it is a collection of values, individual elements can be accessed using the following way.
X[index]
Where index may be forward (0,1,2…) or backward (-1,-2,-3…). Specifying index beyond the scope raises
error.
Slicing a list :Like string one can use slices to retrieve part of a list. E.g.
x=[1,2,3,4,5,6,7,8]
y=x[2:5] # create a list named y that contains element from 2 index position to 4 i.e. 5-1

Operators supported:
Operator Syntax Example
+ (concatenation) List1+list2 [2,3]+[6,2] returns [2,3,6,2]
* ( replication) List1*int [2,3]*2 returns [2,3,2,3]
in 2 in [2,3,77] return True
2 not in [20,3,77] return True
not in
<, > ,<= ,>= ,= =,!= [2,3,5]>[1,1,2] returns True

Finding no. of elements in a list: The len() returns the number of items in a given list.
e.g. x=2,4,6,7]
print(len(x)) # returns 4

Traversing a list: A list is an iterrable object in python. You can traverse each elementsusing loop. E.g.
e.g. x=[1,19,5,66,78,88]
for I in x:
print(I) # I refers to elements directly
Or
for I in range (len(x)):
print(x[i]) # I refers to index of list
Modifying an element
A List is a mutable type in Python. Hence, one can change the value of a given position. When value of a
given position changes, address does not change. As opposed to, in case of Immutable type, when one
change the value of variable , the address changes.
X[3]=90

Nested list:
A list may contain another list as an element. For ex.
X=[„this‟,[5,1,8], 23.0, 45, True] # [5,1,8] is a list in X
A list can be nested further any depth, for ex.
X=[„this‟,[5,1,[3,6,7]], 23.0, 45, True] # [3,6,7] is a list within another list which is again in X

Std. - XII (Science) 191 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
Counting elements in nested list
While counting the number of element, don‟t count all items as a whole. In the above list X has 5 elements,
where asX[1] contains 2 elements and X[1][2] contains 3 elements.
You can use nested list as matrices/ vectors. For example
X=[[2,5,8,],[5,1,8],[9,3,6]]
Here, X is a list of lists i.e. 2 dimensional list having 3 rows and 3 columns value list.

Accessing elements from a 2D list


x[rowpos][colpos] e.g. X[1][0] # returns 5
Iterating a 2D List
for row in range(3):
for col in range(3):
print(X[row][col],end = “ ”)
print()
Accessing elements from adynamic 2D list
Generally, We assume that a 2D list consists of Square or Rectangle box of values. Often the dimension of a
2D list differs i.e. each row may not have same no. of columns (Jagged / uneven). For example suppose you
want to store activity of each day in a 2D list; you have to define 12 rows for months and each of which may
be 30, 28 or 31 days (uneven in months).
X= eval(input(“Enter a list”))
for row in range(len(X)):
for col in range(len(X[row])):
print(X[row][col],end= “ ”)
print()
Now assume that the user is not technically sound in Python, You can write the following program to input
values with formatted output.
X=[] # an empty list
#user input
r=int(input('Enter no. of rows'))
c=int(input('Enter No. of cols'))
for row in range(r):
tmp=[]
for col in range(c):
print('X[ ', row ,'][', col, '] : ', end='')
t=int(input())
tmp.append(t)
X.append(tmp)
#print in matrix format
for row in range(len(X)):
for col in range(len(X[row])):
print('{0:7}'.format(X[row][col]) ,end= '')
print()

Std. - XII (Science) 192 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
LIST FUNCTIONS:

index() Used to get the index of first matched item from the list. It returns index value of
item to search. If item not found, it will return ValueError: n is not in the list.

append() Used to add items to the end of the list. It will add the new item but not return any
value
extend() Used for adding multiple items. With extend we can add multiple elements but
only in form of a list to any list. Even if we want to add single element it will be
passed as an element of a list.
insert() Used to add elements to list at position of our choice i.e. we can add new element
anywhere in the list.
pop() Used to remove item from list. It raises an exception if the list is already empty. By
default, last item will be deleted from list. If index is provided then the given
indexed value will be deleted.
remove() Used to remove an element when index is not known and we want to delete by
provided the element value itself. It will remove first occurrence of given item from
list and return error if there is no such item in the list. It will not return any value.

clear() Use to remove all the items of a list at once and list will become empty.

Del del statement is used to delete the structure of existing list.

count() Used to count the number of occurrences of the item we passed as argument.
If item does not exist in list, it returns Zero.

reverse() Used to reverse the items of a list. It made the changes in the original list and does
not return anything.
sort() Used to sort the items of a list. It made the changes in the original list and sort the
items in increasing order by default. We can specify reverse argument as True to
sort in decreasing order.
sorted() Used to sort the items of a sequence data type and returns a list after sorting in
increasing order by default. We can specify reverse argument as True to sort in
decreasing order.

A tuple is a collection of values of mixed type generally enclosed within parenthesis (). It is an
immutable type.
e.g. x=(90,33,656,44,66,”abcd”,99.00,True)
a list can also be declared as follows
x=() # empty tuple
x= tuple() # empty tuple
x= tuple(“good”)
Std. - XII (Science) 193 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
x=eval(“(3,4,5,6)”)
x=3,
Operators supported:
Operator Syntax Example
+ (concatenation)
* ( replication)
in

not in
<, > ,<= ,>= ,=
=,!=

Functions
Function Description Example
len(tpl) Returns length of a list len([36,6,8]) returns 3
del(tpl[index]) Delete an item from
index
max(tpl) Return the maximum max((20,85,5,84)) : returns 85
item
min(tpl) Return the minimum min((20,85,5,84)) : returns 5
item
Methods
Syntax:
object.method()
Function Description Example
index(item) Return the index position of an
element
count(item) Counts no. of time an element
occurs
Calculate mean, mode and median of a list.

A tuple object like z=(12,22,34,56,78,90,33,23,64,33,66,28,82) stored internally as:


Seq. Value 12 22 34 56 78 90 33 64 33 66 28 82
Forward index 0 1 2 3 4 5 6 7 8 9 10 11
Backward index -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Accessing an element from sequence

You can access a single item from sequence with the corresponding integer indices. Indices in
Python are zero-based. This means the index 0 corresponds to the first (leftmost) item of a
sequence, 1 to the second item, and so on.
Python also support to access elements backward with first index as -1 (rightmost) as follows.
Std. - XII (Science) 194 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

print(y[6]) output : 33
print(z[8]) output : 66
Python also support to access elements backward with first index as -1 (rightmost) as follows.
Ex.
print(y[-3]) output : 90
print(z[-10]) output : 34
Nested Sequence
A sequence can be an element in another sequence. For ex.
X=[“good”,[3,5,7],[2,55,66],45,(5,8,5)]
Accessing an element
print(X[1]) output: [3,5,7]
print(X[2][1]) output: 55
Accessing using slice
print(X[2:4]) output : [[2, 55, 66], 45]

TUPLE FUNCTIONS:

len() Returns number of elements in a tuple

max() Returns the element having maximum value in the tuple

min() Returns the element having minimum value

index() Returns index value of given element in the tuple. It item doesn’t exist,
it will raise ValueError exception.
count() It returns the number of occurrences of the item passed as an
argument. If not found, it returns Zero.
sorted() Used to sort the items of a sequence data type and returns a list after
sorting in increasing order by default. We can specify reverse argument
as True to sort in decreasing order.

A Dictionary is known as mapping object. We can‟t access elements using index. It is generally represented
as key: value pair. A dictionary is a mutable object. But it‟s key are of immutable types.
A dictionary can be declared as follows:
X={} # empty dictionary
y= dict() # empty dictionary

Std. - XII (Science) 195 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
z=eval(“{„id‟:1,‟name‟:‟nirmal‟}”)
# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

To access an element, you have to use key as follows:


X={„r‟:‟Red‟,‟g‟:‟Green‟}
print (X[„r‟])
Note: you can’t apply slice to dictionary
Accessing from nested Dictionary
student={'id':100,'name':'sangram','dob':{'d':5,'mm':1,'yy':2099},'address':'Berhampur'}
print(student['dob']['mm'])
Dictionary is one of the collection type in python. It is generally represented as key: value pair. Dictionary
is a mapping object in python. One can‟t access elements using index. A dictionary is a mutable object. But
its key are of immutable types.
A dictionary can be declared as follows:
X={} # empty dictionary
y= dict() # empty dictionary
z=eval(“{„id‟:1,‟name‟:‟nirmal‟}”)

To access an element, you have to use key as follows:


X={„r‟:‟Red‟,‟g‟:‟Green‟}
print (X[„r‟])
Note: you can’t apply slice to dictionary
Adding/Editing item in a dictionary
Dictionary[„key‟]= value
Deleting elements from a dictionary
del dictionary[key]
dictionary.pop()
dictionary.popitem()
Std. - XII (Science) 196 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
Traversing a dictionary
Each element in a dictionary can be accessed with the help of a loop. Syntax:
for <item> in <dictionary>:
item
Methods:
keys() : return a list sequence of keys.
values() : return a list sequence of values.
get(key,[default]) : return corresponding value , if key exists, else returns Error.
items() : return a sequence of (key, value) pair.
Accessing from nested Dictionary
student={'id':100,'name':'sangram','dob':{'d':5,'mm':1,'yy':2099},'address':'Berhampur'}
print(student['dob']['mm'])
Dictionary Functions:

clear() Used to remove all items from dictionary

get() Used to access the value of given key, if key not found it raises an
exception.
items() Used to return all the items of a dictionary in form of tuples.

keys() Used to return all the keys in the dictionary as a sequence of keys.

values() Used to return all the values in the dictionary as a sequence of values.

update() Merges the key:value pair from the new dictionary into original
dictionary. The key:value pairs will be added to the original dictionary, if
any key already exists, the new value will be updated for that key.
fromkeys() Returns new dictionary with the given set of elements as the keys of the
dictionary.
copy() It will create a copy of dictionary.

popitem() Used to remove the last added dictionary item (key:value pair)

max() Used to return highest value in dictionary, this will work only if all the
values in dictionary are of numeric type.
min() Used to return lowest value in dictionary, this will work only if all the
values in dictionary are of numeric type.
sorted() Used to sort the key:value pair of dictionary in either ascending or
descending order based on the keys.
Statements in Python:

Instructions given to computer to perform any task are called Statements. In Python, we have 3 type of
statements:

Std. - XII (Science) 197 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT

● EMPTY STATEMENTS: When a statement is required as per syntax but we don’t want to execute
anything or do not want to take any action we use pass keyword. Whenever pass is encountered, python
interpreter will do nothing and control will move to the next statement in flow of control.

● SIMPLE STATEMENT: All the single executable statements in Python are Simple Statements.

● COMPOUND STATEMENTS: A group of statements executed as a unit are called compound


statements. Compound statements has a Header which begins with a keyword and ends with colon
(:).There can be at least one or more statements in the body of the compound statement, all indented at
same level.

CONDITIONAL STATEMENTS IN PYTHON:

CONTROL STATEMENTS
Generally, a program executes its statements from beginning to end sequentially. But in many
situations, some statements need to be executed while some are need to be skipped. Besides, some
statement need to be executed repeatedly to concise the code. Such statements are known as control
statements as these are used to control the flow of execution.
Control Statements can be:
 Selection (branching)
 Iteration (looping)
 Jumping

The if Statement
If statements are the conditional statements in python that implements selection/decision construct.
If statement tests a particular condition; if it evaluate to true, some statements are being executed,
otherwise some others.
Syntax#1:
if<condition>:
statements
NB.: statements inside control statements are indented/blocked at same level.
An executable statement may be single or group. Python uses indentation before the statements to
indicate a block of code.
A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose.
Whitespace is used for indentation in Python. All statements with the same distance to the right
belong to the same block of code. If a block has to be more deeply nested, it is simply indented
further to the right
e.g.

Std. - XII (Science) 198 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
x=20
if x%2==0:
print(“even no”)
if test: if test: if test: if test: if test:
suite suite suite suite if test:
[eliftest: else: eliftest: suite
suite]* suite suite [else:
[else: eliftest: suite]
suite] suite else:
else: if test:
suite suite
[else:
suite]

Points to remember
 ‘if’ is a keyword, hence it must be in small case.
 The test condition must return a Boolean type.
 The condition must be followed by a : (colon)
 Block statements must follow same level of indentation.
 If used, the elif statement must have a test condition followed by :& in lower case.
 The else statement must not have a test condition.
 The if or else statement must have at least one statement to execute.
 Variables if used in the test condition / statement must be initialized earlier.

Iterative/looping statements
Python provides 2 kinds of loop:
 Counting loop
 Conditional loop
The for loop
Repeatedly executes one or more statement(s) till all items in the given sequence are over or the
values in a specified range completes.
The for statement

for target in iterable: for target in iterable: for target in iterable: for target in iterable:
suite suite for target in iterable: suite
[else: else: suite
suite] suite [else:
suite]
else:
suite
Points to remember
 ‘for’ is a keyword, hence it must be in small case.
 If iterableis range of values, it must be comma separated with startval, endval , stepval.
 (Both startval and stepval are optional)
 The statement must be followed by a : (colon)
 Block statements must follow same level of indentation and at least one statement.

Std. - XII (Science) 199 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
 If optional ‘else’ statement is used, it must be in small case followed by a :
 The ‘else’ statement must be in the same level of indentation as of for.
 The iterable may be a collection such as list, tuple, string or dictionary.
E.g.1
s=”good morning”
for I in s:
print(I)

The range () function:


The range() function generates a list which is a special sequence type. A sequence in python is a
succession of values bound together by single name.
Syntax:
range([<lowerlimit>],<upperlimit>,[<stepvalue>])
Note:range function() generates numbers uptoupperlimit -1
E.g.#1
for I in range(10):
print(I)
E.g.#1
for I in range(10):
print(I)
if I==5:
break
else:
print(“completed”)
print(“thankyou”)
Note: The else block just after for/while is executed only when the loop is NOT terminated by a break
statement.
Nested for loop
A for loop within another for loop is known as nested for loop.
for I in range(3):
for J in range(3):
print(I)
print()

The while loop


Repeatedly executes one or more statements as long as a condition remains true.
while test: while test: while test: while test:
suite suite suite while test:
[else: else: suite
suite] suite [else:
Std. - XII (Science) 200 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
suite]
else:
suite
Points to remember
 „while‟ is a keyword, hence it must be in small case.
 The test condition must return a Boolean type.
 The condition must be followed by a : (colon)
 Block statements must follow same level of indentation.
 If used, the else statement must not have a test condition.
The else statement must have at least one statement to execute.
E.g#1.
I=1
while I<=10:
print(I)
I +=1
E.g#2.
I=1
while True:
print(I)
I +=1
if I==11 :
break
Nested while loop
while condition:
while condition:
statements
Jumping statements
Used to jump the control flow from one statement to another. Jumping Statements may be:
 break
 continue
 return

The Break Statement


When the break statement encountered in a loop, the control flow transfers out of the loop. In
general, break allows us to exit prematurely from for or while statement.
Note:In nested loops, a break statement terminates the very loop it appears in.
for I in range (1,10):
if I==5:

Std. - XII (Science) 201 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
break
print(I)
The continue statement
The continue statement is used to prematurely end the current iteration and move to the next
iteration. When the continue statement is encountered in a loop, all the statements after the continue
statement are omitted and the loop continues with the next iteration.
for I in range (1,10):
if I<=5:
continue
print(I)
The return statement
The Python return statement is a special statement that you can use inside a function or method to
send the function's result back to the caller. A return statement consists of the return keyword
followed by an optional return value.
deffuncname(parameters): #Called function
statements
return
#__main__
funcname() #calling

The empty statement


An empty statement is useful in a situation, where the code requires a statement but logic does not.
To fill these two requirements simultaneously, empty statement is used. Python offers pass
statement as an empty statement.

MULTIPLE CHOICE QUESTION

1 Find the invalid identifier from the following


a) None (b) address (c) Name (d) _budget24

2 Write the type of tokens from the following:


a) If (b) roll_no

3 Consider a declaration L = (1, 'Python', '3.14'). Which of the following represents the data type of
L?

Std. - XII (Science) 202 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
a) List (b) Tuple (c) Dictionary (d) String

4 Identify the valid arithmetic operator in Python from the following.


a) ? (b) < (c) ** (d) And

5 Which of the following statements is/are not python keywords?


a) False (b) Math (c) while (d) break

6 Which of the following is a valid keyword in Python?


a) False (b) Return (c) Non_local (d) none

7 State True or False.


"Identifiers are names used to identify a variable, function in a program".

8 Identify the invalid identifier out of the options given below.


a) Qwer_12 (b) IF (c) Play123 (d)Turn.over

9 One of the following statements will raise error. Identify the statement that will raise the error.
x,y = 20 #Statement1
z=20,30 #Statement2
a,b=45,90#Statement3

a)Statement1
b)Statement2
c)Statement3
d)None of above will raise error

10 Given the following Tuple


Tup (10, 20, 30, 50)
Which of the following statements will result in an error?
a) print (Tup [0])
b) print (Tup [1:2])
c) Tup.insert (2,3)
d) print(len (Tup))

11 Consider the given expression : 5<10 and 12>7 or not 7>4


Which of the following will be the correct output, if the given expression is evaluated?
a) True
b) False
c) NULL
d) NONE

12 Which of the following will give output as [5,14,6] if lst=[1,5,9,14,2,6]?


a) print(lst[0::2])
b) print(lst[1::2])

Std. - XII (Science) 203 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
c) print(lst[1:5:2])
d) print(lst[0:6:2])

13 The return type of the input() function is


a) string
b) Integer
c) list
d) tuple

14 Which of the following operator cannot be used with string data type?
a)+
b) In
c) *
d) /

15 Consider a tuple tup1 = (10, 15, 25, 30). Identify the statement that will result in an error.
a) print(tup1[2])
b) tup1[2] = 20
c) print(min(tup1))
d) print(len(tup1))

16 Which one of the following is the default extension of a Python file?


a) .exe
b) .p++
c) .py
d) .p

17 Which of the following symbol is used in Python for single line comment?

a)/
b) /*
c) //
d) #

18 Which of these about a dictionary is false?


a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable

19 Which is the correct form of declaration of dictionary?


a) Day=,1:’monday’,2:’tuesday’,3:’wednesday’-
b) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
c) Day=*1:’monday’,2:’tuesday’,3:’wednesday’+
d) Day=,1’monday’,2’tuesday’,3’wednesday’+

Std. - XII (Science) 204 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
20 What will be the output of the following statement:
print(3-2**2**3+99/11)
a) 244
b) 244.0
c) -244.0
d) Error

21 What is the output of following code:


T=(100)
print(T*2)
a) Syntax error
b) (200,)
c) 200
d) (100,100)

22 Identify the output of the following Python statements:


x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]]
y = x[1][2]
print(y)
a) 12.0
b) 13.0
c) 14.0
d) 15.0

23 Select the correct output of the code :


S= "AmritMahotsav @ 75"
A=S.partition (" ")
print (A)
a) ('AmritMahotsav', '@', '75')
b) ['Amrit', 'Mahotsav', '@', '75']
c) ('Amrit', 'Mahotsav @ 75')
d) ('Amrit', '', 'Mahotsav @ 75')
24 Identify the output of the following Python statements.
x=2
while x < 9:
print(x,end='')
x=x+1
a) 12345678
b) 123456789
c) 2345678
d) 23456789

25 Identify the output of the following Python statements.


b=1
for a in range(1, 10, 2):
Std. - XII (Science) 205 | P a g e
Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
b += a + 2
print(b)
a) 31
b) 33
c) 36
d) 39

26 A tuple is declared as T = (2,5,6,9,8). What will be the value of sum(T)?


a) 30 b) 25698 c) Error d) None of these

27 Identify the output of the following Python statements.


lst1 = [10, 15, 20, 25, 30]
lst1.insert( 3, 4)
lst1.insert( 2, 3)
print (lst1[-5])
a) 2
b) 3
c) 4
d) 20

28 Evaluate the following expression and identify the correct answer.


16 - (4 + 2) * 5 + 2**3 * 4
a) 54
b) 46
c) 18
d) 32

29 Fill in the blank.


________________function is used to arrange the elements of a list in ascending order.
a) sort()
b) ascending()
c) arrange()
d) asort()

30 Which of the following will delete key-value pair for key = “Red” from a dictionary D1?
a) delete D1("Red")
b) del D1["Red"]
c) del.D1["Red"]
d) D1.del["Red"]

Std. - XII (Science) 206 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
31 Identify the valid declaration of L:
L = *‘Mon’, ‘23’, ‘hello’, ’60.5’+
a) dictionary
b) string
c) tuple
d) list

32 Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80, 90).
What will be the output of print (tup1 [3:7:2])?
a) (40,50,60,70,80)
b) (40,50,60,70)
c) [40,60]
d) (40,60)

33 If the following code is executed, what will be the output of the following code?
name="ComputerSciencewithPython"
print(name[3:10])
a)CpeSeetyo b) puterSc c) ouccho d) None of these

34 Which of the following statement(s) would give an error during execution of the following code?
tup =(20,30,40,50,80,79)
print(tup) #statement 1
print(tup[3]+50) #statement 2
print(max(tup)) #statement 3
tup [4]=80 #statement 4

a) Statement 1
b) Statement 2
c) Statement 3
d) Statement 4

35 Consider the statements given below and then choose the correct output from the given options:
pride="#G20 Presidency"
print(pride[-2:2:-2])
a) ndsr
b) ceieP0
c) ceieP
d) yndsr

36 Given is a Python list declaration :


Listofnames=["Aman", "Ankit", "Ashish", "Rajan", "Rajat"]
Write the output of:
print (Listofnames [-1:-4:-1])

a. ['Rajat', 'Rajan', 'Ashish']

Std. - XII (Science) 207 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
b. ['Aman', 'Ankit', 'Ashish']

c. ['Aman', 'Ashish', 'Rajat']

d. none of these

37 What will be the output of the following code:


Cities=*‘Delhi’,’Mumbai’+
Cities[0],Cities[1]=Cities[1],Cities[0]
print(Cities)
a)*‘Delhi’,’Mumbai’+
b)*’Mumbai’,‘Delhi’+
c)*’Mumbai’+
d) None of these

38 What will be the output of the following code?


tup1 = (1,2,[1,2],3)
tup1[2][1]=3.14
print(tup1)
a) (1,2,[3.14,2],3)
b) (1,2,[1,3.14],3)
c) (1,2,[1,2],3.14)
d) Error Message

39 Select the correct output of the code:


s=”Python is fun”
p= s.split()
n= “-“.join(*p*0+.upper(),p*1+,p*2+.capitalize()+)
print(n)

a) PYTHON-IS-Fun
b) PYTHON-is-Fun
c) Python-is-fun
d) PYTHON-Is –Fun

40 Which of the following statement(s) would give an error after executing the following code?
Stud={"Murugan":100,"Mithu":95} # Statement 1
print (Stud [95]) # Statement 2
Stud ["Murugan"]=99 # Statement 3
print (Stud.pop()) # Statement 4
print (Stud) # Statement 5
a) Statement 2
b) Statement 4
c) Statement 3
d) Statements 2 and 4

Std. - XII (Science) 208 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
41 What are the possible outcome(s) executed from the following code ?

import random
NAV = ["LEFT","FRONT","RIGHT","BACK"];
NUM = random.randint(1,3)
NAVG = ""
for C in range (NUM,1,-1):
NAVG = NAVG+NAV[C]
print NAVG

a) BACKRIGHT b)BACKRIGHTFRONT
c)BACK d) LEFTFRONTRIGHT
42 Assertion(A): List is an immutable data type
Reasoning(R): When an attempt is made to update the value of an immutable variable, the old variable
is destroyed and a new variable is created by the same name in memory
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True

43 Assertion (A): Python Standard Library consists of various modules.


Reasoning(R): A function in a module is used to simplify the code and avoids repetition.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True

44 Assertion (A) : List can not become key in a dictionary.


Reasoning(R) : Only integers can be keys in a dictionary.
a) Both A and R are true and R is correct explanation of A
b) Both A and R are true but R is not correct explanation of A
c) A is True but R is false
d) R is true but A is false

Output based Questions (2)

1 Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)

2 Rewrite the following code after removing all syntax error(s) and underline each correction done:
Runs=(10,5,0,2,4,3) for I in Runs: if I=0:

Std. - XII (Science) 209 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
print(Maiden Over) else: print(Not
Maiden)
3 Evaluate the following Python expression:
a) 2*3+4**2-5//2
b) 6<12 and not (20>15) or (10>5)
4 Predict the output of the following code:
S="LOST"
L=[10,21,33,4] D={} for I in range(len(S)):
if I%2==0: D[L.pop()]=S[I] else:
D[L.pop()]=I+3 for K,V in D.items():
print(K,V,sep="*")
5 Write the Python statement for each of the following tasks using BUILT-IN functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named, message ends with a full stop / period or not.

6 A list named studentAge stores age of students of a class. Write the Python command to import the
required module and (using built-in function) to display the most common age value from the given list.
OUTPUT BASED QUESTIONS : 3 MARKS
1 Find the output of the following code:
Name="PythoN3.1"
R=""
for x in range(len(Name)):
if Name[x].isupper():
R=R+Name[x].lower()
elif Name[x].islower():
R=R+Name[x].upper()
elif Name[x].isdigit():
R=R+Name[x-1]
else:
R=R+"#"
print(R)
2 Predict the output of the Python code given below:
Text1=”IND-23”
Text2=””
I=0
while I <len(Text1):
if Text1*I+>=”0” and Text1*I+<=”9”:
val = int (Text1[I])
val +=1
Text2+ =str(val)
elif Text1*I+>=”A” and Text1*I+<=”Z”:
Text2+ = (Text1[I+1])
else:
Text2+ =”*”
I+=1
print(Text2)

Std. - XII (Science) 210 | P a g e


Modern
OXFORD PUBLIC SCHOOL, BERHAMPUR COMPUTER SCIENCE ASSIGNMENT
PROBLEM SOLVING QUESTIONS (3 MARKS)
1 Write a function, lenWords(STRING), that takes a string as an argument and returns
a tuple containing length of each word of a string. For example, if the string is "Come let us have some
fun", the tuple will have (4, 3, 2, 4, 4, 3)
2 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as
an argument and displays the names (in uppercase)of the places whose names are longer than 5
characters. For example, Consider the following dictionary

PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}

The output should be:


LONDON NEW YORK
3 Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a numeric value
by which all elements of the list are shifted to left. Sample Input
Data of the list Arr= [10,20,30,40,12,11], n=2
Output:
Arr = [30,40,12,11,10,20]

ANSWERS
1 (a)None , because it is a keyword 23 (d) ('Amrit', ' ', 'Mahotsav @ 75')
2 (a) keyword (b) Identifier 24 (c) 2345678
3 (b) Tuple 25 (c) 36
4 (c) ** 26 (c) 30
5 (b) Math 27 (b) 3
6 (a) False 28 (c) 18
7 True 29 (a) sort
8 (d) Turn.over 30 (b) del D1["Red"]
9 (a) statement 1 31 (d) List
10 (c) Tup.insert (2,3) 32 (d) (40,60)
11 (a) True 33 (b) puterSc
12 (b) print(lst[1::2]) 34 (d)Statement 4
13 (a) string 35 (b) ceieP0
14 (d) / 36 (a) ['Rajat', 'Rajan', 'Ashish']
15 (b) tup1[2] = 20 37 (b) [’Mumbai’,’Delhi’+
16 (c) .py 38 (b) (1,2,[1,3.14],3)
17 (d) # 39 (b)PYTHON-is-Fun
18 (b) The keys of a dictionary can be accessed 40 (d)Statements 2 and 4
using values
19 (a)Day=,1:’monday’,2:’tuesday’,3:’wednesday’- 41 a) BACKRIGHT
20 (c) -244.0 42 (d)
21 (c) 200 43 (a)
22 (d) 15.0 44 (c)



Std. - XII (Science) 211 | P a g e

You might also like