Revise_XI_Python
Revise_XI_Python
KEY POINTS:
Introduction to Python
• Python is an open source, object oriented HLL developed by Guido van Rossum in
1991
• Tokens- smallest individual unit of a python program.
• Keyword-Reserved word that can’t be used as an identifier
• Identifiers-Names given to any variable, constant, function or module etc.
•
Classify the following into valid and invalid identifier
(i) Mybook (ii) Break (iii) _DK (iv) My_book (v) PaidIntrest (vi) s-num
(vii)percent (viii) 123 (ix) dit km (x) class
Ans:(i)valid(ii)Invalid (iii)Valid (iv)valid (v)valid (vi)invalid (‘-‘)is not allowed
(vii)valid(viii)invalid(First Character must be alphabet(ix)invalid (no space is
allowed) (x)invalid (class is a keyword)
13 | P a g e
• Precedence of operators:
( ) Parentheses Highest
** Exponentiation
~ x Bitwise nor
+x, -x Positive, Negative (Unary +, -)
*(multiply), / (divide),//(floor division), %(modulus)
+(add),-(subtract)
& Bitwise and
^ Bitwise XOR
| Bitwise OR
<(less than),<=(less than or equal),>(greater than), >=(greater than or
equal to), ==(equal),!=(not equal)
is , is not
not x Boolean NOT
and Boolean AND
or Boolean OR
Low
Data type:
There are following basic types of variable in as explained in last chapter:
Type Description
bool Stores either value True or False.
int Stores whole number.
float Stores numbers with fractional part.
Complex Stores a number having real and imaginary part (a+bj)
String Stores text enclosed in single or double quote
Stores list of comma separated values of any data type
List
between square [ ] brackets.(mutable )
Stores list of comma separated values of any data type
Tuple
between parentheses ( ) (immutable)
Unordered set of comma-separated key:value pairs ,
Dictionary
within braces {}
14 | P a g e
All questions are of 1 mark.
Q.No. Question
1. Which of the following is a valid identifier:
i. 9type ii. _type iii. Same-type iv. True
2. Which of the following is a relational operator:
i. > ii. // iii. or iv. **
3. Which of the following is a logical operator:
i. + ii. /= iii. and iv. in
4. Identify the membership operator from the following:
i. in ii. not in iii. both i & ii iv. Only i
5. Which one is a arithmetic operator:
i. not ii. ** iii. both i & ii iv. Only ii
6. What will be the correct output of the statement : >>>4//3.0
i. 1 ii. 1.0 iii 1.3333 iv. None of the above
7. What will be the correct output of the statement : >>> 4+2**2*10
i. 18 ii. 80 iii. 44 iv. None of the above
8. Give the output of the following code:
>>> a,b=4,2
>>> a+b**2*10
i. 44 ii. 48 iii. 40 iv. 88
9. Give the output of the following code:
>>> a,b = 4,2.5
>>> a-b//2**2
i. 4.0 ii. 4 iii. 0 iv. None of the above
10. Give the output of the following code:
>>>a,b,c=1,2,3
>>> a//b**c+a-c*a
i. -2 ii. -2.0 iii. 2.0 iv. None of the above
11. If a=1,b=2 and c= 3 then which statement will give the output as : 2.0 from the following:
i. >>>a%b%c+1 ii. >>>a%b%c+1.0 iii. >>>a%b%c iv. a%b%c-1
12. Which statement will give the output as : True from the following :
i. >>>not -5 ii. >>>not 5 iii. >>>not 0 iv. >>>not(5-1)
13. Give the output of the following code:
>>>7*(8/(5//2))
i. 28 ii. 28.0 iii. 20 iv. 60
14. Give the output of the following code:
>>>import math
>>> math.ceil(1.03)+math.floor(1.03)
i. 3 ii. -3.0 iii. 3.0 iv. None of the above
15. What will be the output of the following code:
>>>import math
>>>math.fabs(-5.03)
i. 5.0 ii. 5.03 iii. -5.03 iv . None of the above
Single line comments in python begin with……………….. symbol.
16. i. # ii. “ iii. % iv. _
17. Which of the following are the fundamental building block of a python program.
i. Identifier ii. Constant iii. Punctuators iv. Tokens
18. The input() function always returns a value of ……………..type.
i. Integer ii. float iii. string iv. Complex
19. ……….. function is used to determine the data type of a variable.
i. type( ) ii. id( ) iii. print( ) iv. str( )
20. The smallest individual unit in a program is known as a……………
i. Token ii. keyword iii. punctuator iv. identifier
15 | P a g e
FLOW OF EXECUTION
#Decision making statements in python
Description
Statement
An if statement consists of a boolean expression
if statement
followed by one or more statements.
An if statement can be followed by an optional else
if...else statement statement, which executes when the boolean
expression is false.
If the first boolean expression is false, the next is
checked and so on. If one of the condition is true ,
if…elif…else
the corresponding statement(s) executes, and the
statement ends.
It allows to check for multiple test expression and
nested if…else statements execute different codes for more than two
conditions.
Description
Loop
for loop:
for<ctrl_var>in<sequence>:
It is used to iterate/repeat ifself over a range of
<statement in loop body>
values or sequence one by one.
else:
<statement>
while loop:
while<test_exp>:
The while loop repeatedly executes the set of
body of while
statement till the defined condition is true.
else:
body of else
16 | P a g e
21. Which of the following is not a decision making statement
i. if..else statement ii. for statement iii. if-elif statement iv. if statement
22. …………loop is the best choice when the number of iterations are known.
i. while ii. do-while iii. for iv. None of these
a=5
while a>0:
print(a)
print(“Bye”)
for i in range(1,15,4):
print(i, end=’,’)
for i in range(1,15,5):
print(i,end=’,’)
String: Text enclosed inside the single or double quotes referred as String.
String Operations: String can be manipulated using operators like concatenation (+),
repetition (*) and membership operator like in and not in.
Operation Description
Concatenation Str1 + Str2
Repetition Str * x
Membership in , not in
Comparison str1 > str2
Slicing String[range]
17 | P a g e
String Methods and Built-in functions:
Function Description
len() Returns the length of the string.
capitalize() Converts the first letter of the string in uppercase
split() Breaks up a string at the specified separator and returns a list of substrings.
replace() It replaces all the occurrences of the old string with the new string.
find() It is used to search the first occurrence of the substring in the given string.
It also searches the first occurrence and returns the lowest index of the
index()
substring.
It checks for alphabets in an inputted string and returns True in string
isalpha()
contains only letters.
isalnum() It returns True if all the characters are alphanumeric.
isdigit() It returns True if the string contains only digits.
It returns the string with first letter of every word in the string in uppercase
title()
and rest in lowercase.
count() It returns number of times substring str occurs in the given string.
lower() It converts the string into lowercase
islower() It returns True if all the letters in the string are in lowercase.
upper() It converts the string into uppercase
isupper() It returns True if all the letters in the string are in uppercase.
lstrip() It returns the string after removing the space from the left of the string
rstrip() It returns the string after removing the space from the right of the string
It returns the string after removing the space from the both side of the
strip()
string
It returns True if the string contains only whitespace characters, otherwise
isspace()
returns False.
istitle() It returns True if the string is properly title-cased.
swapcase() It converts uppercase letter to lowercase and vice versa of the given string.
ord() It returns the ASCII/Unicode of the character.
It returns the character represented by the imputed Unicode /ASCII
chr()
number
18 | P a g e
31. Which of the following is not a python legal string operation.
i. ‘abc’+’aba’ ii. ‘abc’*3 iii. ‘abc’+3 iv. ‘abc’.lower()
32. Which of the following is not a valid string operation.
i. Slicing ii. concatenation iii. Repetition iv. floor
33. Which of the following is a mutable type.
i. string ii. tuple iii. int iv. list
34. What will be the output of the following code
str1=”I love Python”
strlen=len(str1)+5
print(strlen)
i. 18 ii. 19 iii. 13 iv. 15
35. Which method removes all the leading whitespaces from the left of the string.
i. split() ii. remove() iii. lstrip() iv rstrip()
36. It returns True if the string contains only whitespace characters, otherwise returns
False. i) isspace() ii. strip() iii. islower() iv. isupper()
37. It converts uppercase letter to lowercase and vice versa of the given string.
i. lstrip() ii. swapcase() iii. istitle() iv. count()
38. What will be the output of the following code.
Str=’Hello World! Hello Hello’
Str.count(‘Hello’,12,25)
i. 2 ii. 3 iii. 4 iv. 5
39. What will be the output of the following code.
Str=”123456”
print(Str.isdigit())
ii. True ii. False iii. None iv. Error
40. What will be the output of the following code.
Str=”python 38”
print(Str.isalnum())
iii. True ii. False iii. None iv. Error
41. What will be the output of the following code.
Str=”pyThOn”
print(Str.swapcase())
i. PYtHoN ii. pyThon iii. python iv. PYTHON
42. What will be the output of the following code.
Str=”Computers”
print(Str.rstrip(“rs”))
i. Computer ii. Computers iii. Compute iv. compute
43. What will be the output of the following code.
Str=”This is Meera\’ pen”
print(Str.isdigit())
i. 21 ii. 20 iii. 18 iv. 19
44. How many times is the word ‘Python’ printed in the following statement.
s = ”I love Python”
for ch in s[3:8]:
print(‘Python’)
i. 11 times ii. 8 times iii. 3 times iv. 5 times
19 | P a g e
45. Which of the following is the correct syntax of string slicing:
i. str_name[start:end] iii. str_name[start:step]
ii. str_name[step:end] iv. str_name[step:start]
46. What will be the output of the following code?
A=”Virtual Reality”
print(A.replace(‘Virtual’,’Augmented’))
i. Virtual Augmented iii. Reality Augmented
ii. Augmented Virtual iv. Augmented Reality
47. What will be the output of the following code?
print(“ComputerScience”.split(“er”,2))
i. [“Computer”,”Science”] iii. [“Comput”,”Science”]
ii. [“Comput”,”erScience”] iv. [“Comput”,”er”,”Science”]
48. Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[:2]
i. he ii. lo iii. olleh iv. hello
49. ………..function will always return tuple of 3 elements.
i. index() ii. split() iii. partition() iv. strip()
50. What is the correct python code to display the last four characters of “Digital India”
i. str[-4:] ii. str[4:] iii. str[*str] iv. str[/4:]
Function Description
append() It adds a single item to the end of the list.
extend() It adds one list at the end of another list
insert() It adds an element at a specified index.
reverse() It reverses the order of the elements in a list.
index() It returns the index of first matched item from the list.
len() Returns the length of the list i.e. number of elements in a list
sort() This function sorts the items of the list.
clear() It removes all the elements from the list.
count() It counts how many times an element has occurred in a list and returns it.
It removes the element from the end of the list or from the specified index
pop()
and also returns it.
20 | P a g e
It removes the specified element from the list
del Statement
It is used when we know the element to be deleted, not the index of the
remove()
element.
max() Returns the element with the maximum value from the list.
min() Returns the element with the minimum value from the list.
51. Given the list L=[11,22,33,44,55], write the output of print(L[: :-1]).
i. [1,2,3,4,5] ii. [22,33,44,55] iii. [55,44,33,22,11] iv. Error in code
52. Which of the following can add an element at any index in the list?
i. insert( ) ii. append( ) iii. extend() iv. all of these
53 Which of the following function will return a list containing all the words of the given string?
i . split() ii. index() i i i . count() iv. list()
54. Which of the following statements are True.
a. [1,2,3,4]>[4,5,6]
b. [1,2,3,4]<[1,5,2,3]
c. [1,2,3,4]>[1,2,0,3]
d. [1,2,3,4]<[1,2,3,2]
i. a,b,d ii. a,c,d iii. a,b,c iv. Only d
55. If l1=[20,30] l2=[20,30] l3=[‘20’,’30’] l4=[20.0,30.0] then which of the following
statements will not return ‘False’:
a. >>>l1==l2 b. >>>l4>l1 c. >>>l1>l2 d. >>> l2==l2
i. b, c ii. a,b,c iii. a,c,d iv. a,d
56. >>>l1=[10,20,30,40,50]
>>>l2=l1[1:4]
What will be the elements of list l2:
i. [10,30,50] ii. [20,30,40,50] iii. [10,20,30] iv. [20,30,40]
57. >>>l=[‘red’,’blue’]
>>>l = l + ‘yellow’
What will be the elements of list l:
i. [‘red’,’blue’,’yellow’] ii. [‘red’,’yellow’] iii. [‘red’,’blue’,’yellow’] iv. Error
58. What will be the output of the following code:
>>>l=[1,2,3,4]
>>>m=[5,6,7,8]
>>>n=m+l
>>>print(n)
i. [1,2,3,5,6,7,8] ii. [1,2,3,4,5,6,7,8] iii. [1,2,3,4][5,6,7,8] iv. Error
59. What will be the output of the following code:
>>>l=[1,2,3,4]
>>>m=l*2
>>>n=m*2
>>>print(n)
>>>l=list(‘computer’)
Column A Column B
21 | P a g e
1. L[1:4] a. [‘t’,’e’,’r’]
2. L[3:] b. [‘o’,’m’,’p’]
3. L[-3:] c. [‘c’,’o’,’m’,’p’,’u’,’t’]
4. L[:-2] d. [‘p’,’u’,’t’,’e’,’r’]
i. 1-b,2-d,3-a,4-c iii. 1-c,2-b,3-a,4-d
ii. 1-b,2-d,3-c,4-a iv. 1-d,2-a,3-c,4-b
Tuples and Dictionary: Tuple is a data structure in python, A tuple consists of multiple
values in a single variable separated by commas. Tuples are enclosed within parentheses ( ).
Tuple is an immutable data type.
Common Tuple Operations:
22 | P a g e
Operation Description
Concatenation Tuple1 + Tuple2
Repetition Tuple * x
Index Tuple.index(ele)
Count Tuple.count(ele)
Slicing Tuple[range]
Membership in and not in
Tuple Functions:
Function Description
del statement It is used to delete the tuple.
It returns the index of first matched item from the
index( )
tuple.
Returns the length of the tuple i.e. number of
len( )
elements in a tuple
It counts how many times an element has occurred
count( )
in a tuple and returns it.
It returns True if a tuple is having at least one item
any ( )
otherwise False.
It is used to sort the elements of a tuple. It returns
sorted( )
a list after sorting.
sum( ) It returns sum of the elements of the tuple.
Returns the element with the maximum value
max( )
from the tuple.
Returns the element with the minimum value from
min( )
the tuple.
Dictionary: Python Dictionaries are a collection of some key-value pairs .Dictionaries are
mutable unordered collections with elements in the form of a key:value pairs that associate
keys to values. Dictionaries are enclosed within braces {}
Function Description
It returns the content of dictionary as a list of
items( )
tuples having key-value pairs.
keys( ) It returns a list of the key values in a dictionary
23 | P a g e
It returns a list of values from key-value pairs in a
values( )
dictionary
It returns the value for the given key ,if key is not
get( )
available then it returns None
copy( ) It creates the copy of the dictionary.
Returns the length of the Dictionary i.e. number
len( )
of key:value pairs in a Dictionary
It is used to create dictionary from a collection of
fromkeys( )
keys(tuple/list)
clear( ) It removes all the elements from the Dictionary.
It sorts the elements of a dictionary by its key or
sorted( )
values.
It removes the last item from dictionary and also
popitem( )
returns the deleted item.
Returns the key having maximum value in the
max( )
Dictionary.
Returns the key having minimum value in the
min( )
Dictionary.
>>>tup1=(1,2,4,3)
>>>tup2=(1,2,3,4)
24 | P a g e
76. Which function is used to return a value for the given key.
i. len( ) ii. get( ) iii. keys( ) iv. None of these
79. Which of the following will delete key-value pair for key=’red’ form a dictionary D1
i. Delete D1(“red”) ii. del. D1(“red”) iii. del D1[“red”] iv. del D1
80. Which function is used to remove all items form a particular dictionary.
i. clear( ) ii. pop( ) iii. delete iv. rem( )
1. He want to add a new element 60 in the tuple, which statement he should use out of the
given four.
25 | P a g e
i. >>>t+(60)
ii. >>>t + 60
iii. >>>t + (60,)
iv. >>>t + (‘60’)
92 Rahul wants to delete all the elements from the tuple, which statement he should use
i. >>>del t
ii. >>>t.clear()
iii. >>>t.remove()
iv. >>>None of these
93 Rahul wants to display the last element of the tuple, which statement he should use
i. >>> t.display()
ii. >>>t.pop()
iii. >>>t[-1]
iv. >>>t.last()
94 Rahul wants to add a new tuple t1 to the tuple t, which statement he should use
i. >>>t+t1
ii. >>>t.add(t1)
iii. >>>t*t1
iv. None of these
95 Rahul has issued a statement after that the tuple t is replace with empty tuple, identify the statement
he had issued out of the following:
i. >>> del t
ii. >>>t= tuple()
iii. >>>t=Tuple()
iv. >>>delete t
96 Rahul wants to count that how many times the number 10 has come:
i. >>>t.count(10)
ii. >>>t[10]
iii. >>>count.t(10)
iv. None of these
97 Rahul want to know that how many elements are there in the tuple t, which statement he should use
out of the given four
i. >>>t.count()
ii. >>>len(t)
iii. >>>count(t)
iv. >>>t.sum()
98 >>>t=(1,2,3,4)
Write the statement should be used to print the first three elements 3 times
i. >>>print(t*3)
ii. >>>t*3
iii. >>>t[:3]*3
iv. >>>t+t
99 Match the output with the statement given in column A with Column B
1. >>>tuple([10,20,30]) a. >>> (10,20,30)
2. >>>(“Tea”,)* 3 b. >>> 2
3. >>>tuple(“Item”) c. >>> ('Tea', 'Tea', 'Tea')
4. >>>print(len(tuple([1,2]))) d. >>> ('I', 't', 'e', 'm')
i. 1-b,2-c,3-d,4-a
ii. 1-a,2-c,3-d,4-b
iii. 1-c,2-d,3-a,4-a
iv. 1-d,2-a,3-b,4-c
26 | P a g e
100 Write the output of the following code:
>>>d={‘name’:’rohan’,’dob’:’2002-03-11’,’Marks’:’98’}
>>>d1={‘name’:‘raj’)
>>>d1=d.copy()
>>>print(“d1 :”d1)
i. d1 : {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'}
ii. d1 = {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'}
iii. {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'}
iv. (d1 : {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'})
27 | P a g e
Built-in Functions
Function Description
eval() It is used to evaluate the value of a string and returns numeric value
min() and Both can take two or more arguments and returns the smallest and largest
max() value respectively.
abs() It returns the absolute value of a single number.
type() It is used to determine the type of variable.
round() It returns the result up to a specified number of digit .
len() Returns the length of an object.
range() It is used to define a series of numbers.
Functions form math module
ceil(x) It returns the smallest integer that is greater than or equal to x.
floor(x) It returns the largest integer that is less than or equal to x.
It returns the value of xy , where x and y are numeric expressions, and
pow(x,y)
returns the output in floating point number.
sqrt(x) Returns the square root of x.
Functions from random module
random() It generates a random number from 0 to 1.
It generates an integer between its lower and upper argument. By default
randrange()
the lower argument is 0 and upper argument is 1
It is used for making a random selection from a sequence like list, tuple or
choice()
string.
shuffle() It is used to shuffle or swap the contents of a list.
102 Name the statement that sends back a value from a function
i. print ii. input iii. return iv. None
108 What is the output of the functions shown below? >>>min(max(False,-3,-4), 2,7)
i. 2 i i . False iii. -3 iv. -4
>>>x=3
>>>eval('x**2')
i. Error ii. 1 iii. 9 iv. 6
110 Which of the following functions does not throw an error?
i. ord() ii. ord(‘ ‘) iii. ord(”) iv. ord(“”)
111 What is the output of below program?
def say(message, times = 1):
print(message * times , end =’ ‘)
say(‘Hello and’)
say('World', 5)
i. Hello and WorldWorldWorldWorldWorld
ii. Hello and World 5
iii. Hello and World,World,World,World,World
iv. Hello and HelloHelloHelloHelloHello
112 What is a variable defined inside a function referred to as?
i. A global variable ii. A volatile variable
iii. A local variable iv. An automatic variable
113 How many keyword arguments can be passed to a function in a single function call?
i. zero ii. one i i i . zero or more i v . one or more
30 | P a g e
114 How are required arguments specified in the function heading?
i. identifier followed by an equal to sign and the default value
ii. identifier followed by the default value within backticks (“)
iii.identifier followed by the default value within squarebrackets ([ ])
iv. identifier
115 What is returned by
>>> math.ceil(3.4)?
i. 3 ii. 4 iii. 4.0 iv. 3.0
128 Which of the following statements are True out of the given below:
31 | P a g e
1. More than one value(s) can be returned by a function
2. The variable declared inside a function is a Global variable.
3. Once the function is defined , it may be called only once
4. A function is used by invoking it
i. 1 & 2 ii. 1 & 4 iii. 2 & 3 iv. 2 & 4
129 Match the columns:
A B
1. max() a. will compute x**y
2. sqrt(x) b. will select a option randomly
3. choice() c. will return the largest value
4. pow(x,y) d. will compute (x)1/2
i. 1-a,2-b,3-c,4-d iii. 1-c,2-d,3-b,4-a
ii. 1-d,2-a,3-c,4-b iv. 1-b,2-c,3-d,4-a
Answers:
33 | P a g e
120 ii 121 ii 122 i 123 ii 124 iii 125 ii 126 ii
127 iii 128 ii 129 iii 130 i 131 iii 132 iv 133 iii
134 iv 135 iii 136 i 137 i 138 i 139 iii 140 ii
141 i 142 iii 143 ii 144 ii 145 ii 146 iv 147 iii
Data File Handling
Key Points of Data File Handling
File:- A file is a collection of related data stored in computer storage for future data retrieval.
Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line includes a sequence of characters.
2. Binary Files: A binary file is any type of file that is not a text file. WORKING WITH TEXT FILES:
Basic operations with files:
a. Read the data from a file
b. Write the data to a file
c. Append the data to a file
d. Delete a file a. Read the data from a file:
There are 3 types of functions to read data from a file. –read( ), readline( ), readlines( )
Binary files are used to store binary data such as images, video files, audio files etc. They store data in the binary
format (0‘s and 1‘s).
In Binary files there is no delimiter for a line. To open files in binary mode, when specifying a mode, add 'b' to it.
Pickle module can be imported to write or read data in a binary file.
CSV (Comma Separated Values) is a file format for data storage which looks like a text file. The information is
organized with one record on each line and each field is separated by comma.
CSV File Characteristics
• One line for each record
• Comma separated fields
• Space-characters adjacent to commas are ignored
• Fields with in-built commas are separated by double quote characters.
Compare text files, binary files and csv files and write pros and cons of each of them .
Text Files Binary Files CSV Files
It is very common
It is capable to handle format and platform
1 textual data. It is capable to handle large file. independent.
Any text editors like No specific programs can be used to It can be read using text
notepad can be used to read read them, python provides functions to editors like notepads and
3 them. read data. spreadsheet software.
It terminates a line
automatically when the
delimiter is not used
4 Every line ends with EOL. There is no specific EOL character. after data.
34 | P a g e