01 Python Revision Tour
01 Python Revision Tour
CHAPTER- 1
PYTHON REVISION TOUR
ABOUT PYTHON:
1. Python is a high-level programming language developed by Guido
Van Rossum. The language was released in February 1991 and got
its name from a BBC comedy series “Monty Python’s Flying Circus”.
2. It is an interpreted and platform independent language i.e. the
same code can run on any operating system.
3. It can be used to follow both procedural and object-oriented
approaches to programming.
4. It is free to use and based on two programming languages: ABC language and Modula-3.
2. 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. Examples: and, while, del, with, True, None, False, return, try etc.
3. 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.
2|Page
4. Literals: The data items that have a fixed value are called Literals. If a data item holds
numeric values it will be known as Numeric Literal, if it contains String values it will be
known as String Literal and so on. It means the type of value stored by the data item
will decide the type of Literal. Python has one special literal which is None to indicate
absence of value.
5. 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. The operator precedence in Python is as follows:
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.
6. Punctuators: These are the symbols that are used to organize sentence structure in
programming languages. Common punctuators are: ‘ ‘’ # $ @ [] {} = : ; () , .
7. 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 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.
8. 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.
3|Page
9. 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,
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 c will be decided at run time on
the basis of value of a and b.
10. Type Casting: In Type casting, the data type conversion of a variable is done explicitly
by using some built-in functions. Here, we can say that we force the variable by
applying a built-in function to change the data type and it is not done at run time.
Some common type casting functions are int(), float(), str(), list(), tuple(), dict() etc.
4|Page
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.
3. Boolean allows to store only two values True and False where True means 1 and False
means 0 internally.
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:
A. STRING:
5|Page
B. LIST:
● Lists can hold multiple elements of the same or different data types.
● Lists are mutable in nature which means the values can be updated without
assigning a new memory location. It is denoted by square brackets [].
● ‘for’ loop can be used to traverse a list.
● We can add (join) a list with another list only and not with int, float or string type.
Joining of 2 or more can be done using ‘+’.
● We can concatenate a list with an integer only. Concatenation (Replication) can be
done in a list using ‘*’.
● Slicing means extracting a part of list. Slicing in a list is done in same way as in
String.
C. TUPLE:
● Tuples can also hold multiple elements of the same or different data types like lists
but tuples are immutable in nature. These are denoted by round brackets ().
● If multiple values are assigned to a single variable then by default the type of
variable will be tuple.
● Tuples can be traversed in same way as Strings using ‘for’ loop.
● Slicing, Concatenation (Replication) and Joining operations can also be performed
on Tuples in same way as of Strings.
6|Page
WIDELY USED BUILT-IN FUNCTIONS IN PYTHON:
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.
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.
7|Page
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.
TUPLE FUNCTIONS:
len() Returns number of elements in a tuple
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.
8|Page
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.
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:
● 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
9|Page
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.
10 | P a g e
for loop in python is used when we know the number of iterations.
for loop is used to create loop where we are working on sequence data types.
To repeat the loop n number of times in for loop we use range function in which we
can specify lower limit and upper limit.
range function will generate set of values from lower limit to upper limit. We can also
specify the step value which is +1 by default.
Step value can be in -ve also to generate set of numbers in reverse orders.
while loop in python is also called as entry-controlled loop in which entry is loop is
allowed only if the condition is true.
There are 4 main elements of while loop:
● Initialization: In while loop, we cannot use a variable in test condition without
initializing it with a starting value. So, we will specify the starting value to the
variable to be used in loop.
● Test Condition: We will specify a test condition in the header of the loop. If this
condition will be True then only the body of the loop will be executed else the loop
will not get executed at all.
● Body of loop: We will write the statements to be executed if the test condition will
be True.
● Update Statement: In while loop, we have to increase and decrease the value of
variable used in test condition else the loop will result in infinite loop.
break keyword is used to take control out of the loop for any given condition. When
break is encountered in a loop the flow of control jumps to the very next statement
after the loop.
continue keyword is used to skip the execution of remaining statements inside the
loop and takes control to next iteration..
11 | P a g e
MULTIPLE CHOICE QUESTION
1 Find the invalid identifier from the following
a) None
b) address
c) Name
d) pass
9 One of the following statements will raise error. Identify the statement that will
raise the error.
12 | P a g e
a)
b)
c)
d) None of above will raise error
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, and 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))
13 | P a g e
c) .py
d) .p
17 Which of the following symbol is used in Python for single line comment?
a) /
b) /*
c) //
d) #
14 | P a g e
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
15 | P a g e
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"]
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])
34 Which of the following statement(s) would give an error during execution of the
following code?
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
16 | P a g e
Write the output of:
print (Listofnames [-1:-4:-1])
a) PYTHON-IS-Fun
b) PYTHON-is-Fun
c) Python-is-fun
d) PYTHON-Is –Fun
42 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
17 | P a g e
print (Stud) # Statement 5
a) Statement 2
b) Statement 4
c) Statement 3
d) Statements 2 and 4
a) False
b) True
c) Error
d) None
18 | P a g e
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
Weightage : 2 marks
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:
print(Maiden Over)
else:
print(Not Maiden)
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.
19 | P a g e
Weightage : 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)
Programming Practice
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)
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
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
20 | P a g e
Data of the list
Arr= [ 10,20,30,40,12,11],
n=2
Output:
Arr = [30,40,12,11,10,20]
21 | P a g e