Revision Tour of Python Class XII
Revision Tour of Python Class XII
Basics of Python
Observe the program first then memorize the definitions:
➔ The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
➔ This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_) Thus, an identifier
cannot start with a digit.
➔ for multi line comment use ‘‘‘ text ’’’ (in triple quotes)
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable can
hold and the operations that can be performed on that data.
Number
Number data type stores numerical values only. It is further classified into three different types: int, float and
complex.
Try the following statements on system in shell mode and observe the output:
num1 = 10 #(integer positive value )
type(num1)
num2 = -1210 #(integer negative value)
type(num2)
float1 = -1921.9 #(float1 variable contain decimal value so it contains float value)
type(float1)
float2 = -9.8*10**2 #(float2 variable contain decimal value so it contains float value)
print(float2, type(float2))
var2 = -3+7.2j #(var2 variable contain complex value)
print(var2, type(var2))
Boolean
var3= True # (var3 variable contain Boolean Value)
print(type(var3)) # print type Bool
Variables of simple data types like int, float, boolean, etc. hold single values. But such variables are not useful to
hold a long list of information, for example, names of the months in a year, names of students in a class, names and
numbers in a phone book or the list of artefacts in a museum. For this, Python provides data types like tuples, lists,
dictionaries and sets.
Sequences can used as datatype in python
A Python sequence is an ordered collection of items, where each item is indexed by an integer. The three types of
sequence data types available in Python are Strings, Lists and Tuples. A brief introduction to these data types is as
follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters including spaces.
String values are enclosed either in single quotation marks (e.g., ‘KV’) or in double quotation marks (e.g.,
“Vidyalaya”). The quotes are not a part of the string, they are used to mark the beginning and end of the string for
the interpreter. For example:
Write your examples here:
Prove this statement using proper example: We cannot perform numerical operations on strings, even when the
string contains a numeric value.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square brackets [ ]. In list we can
change the items so we can say it’s a mutable datatype
#To create a list
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1) # printing the elements of list1
Output: [5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).Once created, we
cannot change the tuple (Records cannot be changed) – i.e. we can say immutable datatype.
Tuple can be defined as
T=5,
T=(5,)
T=5,6,7,8
T= ‘a’,’b’,’c’,5,6,7
T=(5,6,’r’,’s’,’wel’)
#create a tuple tuple1
tuple1 = (10, 20, "KV", 5.5, 'a')
print(tuple1) #printing the elements of the tuple tuple1
Output: (10, 20, "KV", 5.5, 'a')
(D) Dictionary
Dictionary in Python holds data items in key : value pairs. Items in a dictionary are enclosed in curly braces { }.
Every key is separated from its value using a colon (:) sign. The key : value pairs of a dictionary can be accessed
using the key. The keys are usually strings and their values can be any data type. In order to access any value in the
dictionary, we have to specify its key in square brackets [ ].
#create a dictionary
dict1 = {'Fruit':'Apple', 1:'Monday', 'Price Rs':120}
print(dict1)
output: {'Fruit': 'Apple', 1: ‘Monday’,'Price Rs': 120}
print(dict1['Price Rs'])
output: 120
print(dict1[1])
output:’Monday’
(E) None
None is a special data type with a single value. It is used to signify the absence of value in a situation. None
supports no special operations, and it is neither False nor 0 (zero).
myVar = None
print(type(myVar))
<class 'NoneType'>
print(myVar)
Mutable and Immutable Data Types
Variables whose values can be changed after they are created and assigned without changing their memory location
are called mutable. Variables whose values cannot be changed after they are created and assigned or upon changing
values their memory location is changed, are called immutable. 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 new memory
location.
Exercise: Define a variable by assigning a value, find and note its ID, change the value and again find its ID, now
observe the difference and do it for different data types.
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an expression contains different kinds of
operators, precedence determines which operator should be applied first. Higher precedence operator is evaluated
before the lower precedence operator. (Simply apply BODMAS rules)
Order of Precedence (higher to lower)
Flow of Control
Selection
The if statement has following syntaxes:
1)
if condition:
statement(s)
2) else:
if condition: statement(s)
statement(s)
3) if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
NOTE
Indentation
Python uses indentation for block as well as for nested block structures. Leading whitespace
(spaces and tabs) at the beginning of a statement is called indentation. In Python, the same level of
indentation associates statements into a single block of code. The interpreter checks indentation
levels very strictly and throws up syntax errors if indentation is not correct. It is a common
practice to use a single tab for each level of indentation.
Repetition
Repetition of a set of statements in a program is made possible using looping constructs.
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is executed
for each of the items in the range. These values can be either numeric, or they can be elements of
a data type like a string, list, tuple or even dictionary.
Syntax of the for Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
The ‘while’ Loop
The while statement executes a block of code repeatedly as long as the control condition of the
loop is true. The control condition of the while loop is executed before any statement inside the
loop is executed. After each iteration, the control condition is tested again and the loop continues
as long as the condition remains true. When this condition becomes false, the statements in the
body of loop are not executed and the control
is transferred to the statement immediately following the body of while loop. If the condition of
the while loop is initially false, the body is not executed even once.
Syntax of while Loop
while test_condition:
body of while
Break and Continue Statement
In certain situations, when some particular condition occurs, we may want to exit from a loop
(come out of the loop forever) or skip some statements of the loop before continuing further in the
loop. These requirements can be achieved by using break and continue statements, respectively.
STRINGS IN PYTHON
Python strings are characters enclosed in quotes of any type – single quotation marks, double
quotation marks and triple quotation marks. An empty string is a string that has 0 characters.
Python strings are immutable.
Strings are sequence of characters, where each character has a unique position-id/index. The
indexes of a string begin from 0 to (length -1) in forward direction and -1,-2,-3,….,-length in
backward direction.
STRING SLICES
In Python, the term ‘string slice’ refers to a part of the string, where strings are sliced using a
range of indices. That is, for a string say name, if we give name[n:m] where n and m are integers
and legal indices, Python will return a slice of the string by returning the characters falling
between indices n and m starting at n, n+1, n+2, … till m-1.
Then,
word[0:7] will give ‘amazing’
word[0:3] will give ‘ama’
word[2:5] will give ‘azi’
word[-7:-3] will give ‘amaz’
word[-5:-1] will give ‘azin’
In a string slice, you give the slicing range in the form [<begin-index>:<last>]. If, however, you
skip of the begin-index or last, Python will consider the limits of the string, i.e., for missing begin
index, it will consider 0 (the first index) and for mission last value, it will consider length of the
string. Consider the following examples to understand this:
word[:7] will give ‘amazing’
word[:5] will give ‘amazi’
word[3:] will give ‘zing’
word[5:] will give ‘ng’
Note: Using the same string slicing technique, you will find that for any index n, s[:n]+s[n:] will
give you original string s.
STRING FUNCTIONS AND METHODS
Every string object that you create in Python is actually an instance of String class. The string
manipulation methods that are being discussed below can be applied to string as per following
syntax:
<stringObject>.<methodname>()
1. string.capitalize(): Returns a copy of the string with its first character capitalized
Exmple: ‘true’.capitalize() will return ‘True’
‘i love my India’.capitalize() will return ‘I love my India’
2. string.title(): Returns a copy of the string with first character of each work capitalized.
Example: ‘true’.title() will return ‘True’
‘i love my india’.capitalize() will return ‘I Love My India’
3. string.upper(): Returns a copy of the string converted to uppercase. Examples:
string.upper() will return ‘HELLO’
string2.upper() will return ‘THERE’
string3.upper() will return ‘GOLDY’
4. string.lower(): Returns a copy of the string converted to lowercase. Examples:
string.lower() will return ‘hello’
string2.lower() will return ‘there’
string3.lower() will return ‘goldy’
5. string.count(str): Returns the count of an string in the given string. Examples:
‘I love my india’.count(‘i’) will return 2
‘it goes as – ringa ringa roses’.count(‘ringa’) will return 2
6. string.find(sub[,start,end]): Returns the lowest index in the string where the substring sub is
found within the slice range of start and end. Returns -1 if sub is not found. Example:
string = ‘it goes as – ringa ringa roses’
sub = ‘ringa’
string.find(sub) will return 13
string.find(sub,15,22) will return -1
string.find(sub,15,25) will return 19
7. string.index(str): Returns the lowest index in the sting where the substring is found. Example:
‘I love my India’.index(‘o) will return 3
‘I love my India’.index(‘my’) will return 7
8. string.isalnum(): Returns True if the characters in the string are alphanumeric (alphabets or
numbers) and there is at least one character, False otherwise. Example:
string =”abc123”
string2 = ‘hello’
string3 = ‘12345’
string4 = ‘ ’
string.isalnum() will return True
string2.isalnum() will return True
string3.isalnum() will return True
string4.isalnum() will return False
9. string.islower(): Returns True if all cased characters in the string are lowercase. Examples:
string = ‘hello’
string2 = ‘THERE’
string3 = ‘Goldy’
string.islower() will return True
string2.islower() will return False
string3.islower() will return False
10. string.isupper(): Returns True if all cased characters in the string are uppercase. Examples:
string.isupper() will return False
string2.isupper() will return True
string3.isupper() will return False
11. string.isspace(): Returns True if there are only whitespace characters in the string. Examples:
string = “ “
string2 = “”
string.isspace() will return True
string2.isspace() will return False
12. string.isalpha(): Returns True if all characters in the string are alphabetic and there is at least
one character, False otherwise. Example:
string.isalpha() will return False
string2.isalpha() will return True
string3.isalpha() will return False
13. string.isdigit(): Returns True if all the characters in the string are digits. There must be at least
one character, otherwise it returns False. Example:
string.isdigit() will return False
string2.isdigit() will return False
string3.isdigit() will return True
14. string.split([<sep>]): This function splits the string to form a list of strings.
If we do not provide any argument to split then by default it will split the given string considering
whitespace as a separator, e.g.,
“I Love Python”.split() will give [‘I’, ‘Love’, ‘Python’]
If we provide a string or a character as an argument to split(), then the given string is divided into
parts considering the given string/character as separator and separator character is not included in
the split strings, e.g.,
“I Love Python”.split(‘o’) will give [‘I L’, ’ve Pyth’, ’n’]
15. string.partition(<sep>): The partition() method searches for a specified string, and splits the
string into a tuple containing three elements. The first element contains the part before the
specified string. The second element contains the specified string. The third element contains the
part after the string.
Example: ‘I Love my India’.partition(‘my’) will give (‘I Love ’, ‘my’, ‘ India’)
16. string.lstrip([chars]): Returns a copy of the string with leading characters removed.
If used without any argument, it removes the leading whitespaces.
One can use optional chars argument to specify a set of characters to be removed.
The chars argument is not a prefix; rather, all combinations of its values (all possible substrings
from the given string argument chars) are stripped when they lead the string.
Examples:
string = “hello”
string.lstrip() will return ‘hello’
string2 = ‘There’
string2.lstrip(‘the’) will return ‘There’
string2.lstrip(‘The’) will return ‘re’
string2.lstrip(‘he’) will return ‘There’
string2.lstirp(‘Te’) will return ‘here’
string2.lstrip(‘Teh’) will return ‘re’
string2.lstrip(‘heT’) will return ‘re’
“saregamapadhanisa”.lstrip(“tears”) will return ‘gamapadhanisa’
“saregamapadhanisa”.lstrip(“races”) will return ‘gamapadhanisa’
17. string.rstrip([chars]): Returns a copy of the string with trailing characters removed.
If used without any argument, it removes the trailing whitespaces.
The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix; rather, all combinations of its values are stripped.
Examples:
string = ‘hello’
string.rstrip() will return ‘hello’
string2 = ‘There’
string2.rstripe(‘ere’) will return ‘Th’
string2.rstrip(‘care’) will return ‘Th’
string2.rstrip(‘car’) will return ‘there’
“saregamapadhanisa”.rstrip(“tears”) will return “saregamapadhani”
“saregamapadhanisa”.rstrip(“races”) will return “saregamapadhani”
18. string.strip([chars]): Returns a copy of the string with both leading and trailing characters
removed.
For example,
string=’hello’
len(string) will return 5
LISTS IN PYTHON
The Python lists are containers that are used to store a list of values of any type. Python lists are
mutable i.e., you can change the elements of a list in place. Which means Python will not create a
fresh list when you make changes to an element of a list. List is a type of sequence like strings and
tuples.
Difference from Strings
You cannot change individual elements of a string in place, but Lists allow you to do so. That is,
following statement is fully valid for Lists:
L[i] = <element>
For example, consider the same vowels list crated above. Now if you want to change some of
these vowels, you may write something as show below:
vowels[0] = ‘A’
print(vowels)
[‘A’,’e’,’i',’o’,’u’]
List Functions
1. len() function
This function returns the length of a list i.e. this function returns number of elements present in the
list. It is used as per following format:
len(<list>)
For example for a list L1 = [13,18,11,16,18,14]
len(L1) will return 6
2. list() function
This function converts the passed argument to a list. The passed argument could be a string, a list
or even a tuple. It is used as per following format:
list(<argument>)
For example for a string s = “Computer”
list(s) will return [‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
3. The append() function
The append() function adds an item to the end of the list. It works as per following syntax:
List.append(<item>)
For example, to add a new item “yellow” to a list containing colours, you may write:
colours =[“red”,”green”,”blue”]
colours.append(“yellow”)
print(colours)
[“red”,”green”,”blue”,”yellow”]
4. The extend() function
The extend() method is also used for adding multiple elements (given in the form of a list) to a
list. The extend() function works as per following format:
List.extend(<list>)
That is extend() takes a list as an argument and appends all of the elements of the argument list to
the list object on which extend() is applied. Consider following example:
t1=[‘a’,’b’,’c’]
t2=[‘d’,’e’]
t1.extend(t2)
print(t1)
[‘a’,’b’,’c’,’d’,’e’]
print(t2)
[‘d’,’e’]
5. The insert() function
If you want to insert an element somewhere in between or any position of your choice, both
append() and extend()are of no use. For such a requirement insert() is used.
The insert() function inserts an item at a given position. It is used as per following syntax:
List.insert(<pos>,<item>)
The first argument <pos> is the index of the element before which the second argument <item> to
be added. Consider the following example:
t1=[‘a’,’e’,’u’]
t1.insert(2,’i')
print(t1)
[‘a,’e’,’i',’u’]
For function insert(), we can say that:
list.insert(0,x) will insert element x at the front of the list i.e. at index 0.
list.insert(len(list),x) will insert element x at the end of the list i.e. index equal to length of the list
6. The count() function
This function returns the count of the item that you passed as argument. If the given item is not in
the list, it returns zero. It is used as per following format:
List.count(<item>)
For instance:
L1 = [13,18,20,10,18,23]
print(L1.count(18))
2
print(L1.count(28))
0
7. The Index() function
This function returns the index of first matched item from the list. It is used as per following
format:
List.index(<item>)
For example, for a list L1 = [13,18,11,16,18,14]
print(L1.index(18))
1
However, if the given item is not in the list, it raises exception ValueError.
8. The remove() function
The remove() method removes the first occurrence of given item from the list. It is used as per
following format:
List.remove(<value>)
The remove() will report an error if there is no such item in the list. Consider the example:
t1=[‘a’,’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘a’)
print(t1)
[’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘p’)
print(t1)
[’e’,’i',’q’,’a’,’q’,’p’]
print(t1.remove(‘k’))
ValueError
9. The pop() method
The pop() is used to remove the item from the list. It is used as per the following syntax:
List.pop(<index>)
Thus, pop() removes an element from the given position in the list, and return it. If no index is
specified, pop() removes and returns the last item in the list.
t1 = [‘k’,’a’,’i',’p’,’q’,’u’]
ele = t1.pop(0)
print(ele)
‘k’
10. The reverse() function
The reverse() reverses the item of the list. This is done “in place” i.e. id does not create a new list.
The syntax to use reverse method is:
List.reverse()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.reverse()
print(t1)
[‘p’,’q’,’a’,’q’,’i',’e’]
11. The sort() function
The sort() function sorts the items of the list, by default in increasing order. This is done “in
place” i.e. it does not create a new list. It is used as per following syntax:
List.sort()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.sort()
print(t1)
[‘a’,’e’,’i',’p’,’q’,’q’]
To sort a lit in decreasing order using sort(), you can write:
List.sort(reverse=True)
12. min() function
This function returns the minimum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the minimum value from a given
list. Strings are compared using its ordinal values/Unicode values. This function is used as per
following format:
min(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
min(L1) will return 11 and min(L2) will return ‘U’
13. max() function
This function returns the maximum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the maximum value from a given
list. Strings are compared using its ordinal values/Unicode values. This function is used as per
following format:
max(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
max(L1) will return 18 and max(L2) will return ‘o’
14. sum() function
This function returns the total of values present in the list. This function will work only if all
elements of the list are numbers. This function gives the total of all values from a given list. This
function is used as per following format:
sum(<list>)
For example L1=[13,18,11,16,18,14] then sum(L1) will return 90
15. The clear() function
This method removes all the items from the list and the list becomes empty list after this function.
This function returns nothing. It is used as per following format:
List.clear()
For instance:
L1=[2,3,4,5]
L1.clear()
print(L1)
[]