Professional Documents
Culture Documents
Python Revision Tour
Python Revision Tour
CHAPTER- 1
PYTHON REVISION TOUR
INTRODUCTION TO 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.
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.
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.
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)
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
Arithmetic 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 :
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 evaluates to True if either of its operands evaluates to True; False if both operands evaluate to False.
Example
In an expression x or y, if the first operand has false, then return second operand y as result, otherwise return x.
Example
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
In an expression x or y, if the first operand has false, then return first operand x as result, otherwise return y.
Example
Works on single operand(unary operator). Negates the value in an expression. For example.
Example
Bitwise operators
Identity operator
Membership operator
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.
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
X=45
a=b=c=90
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,
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
While evaluating an arithmetic expression, Python follows the Precedence (priority) of operators as well as
associativity of operators as follow.
Precedence of Operators
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 (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
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)
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.
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
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])
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.
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
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
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.
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.
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:
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
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
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.
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.
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.
3 Consider a declaration L = (1, 'Python', '3.14'). Which of the following represents the data type of
L?
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
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))
17 Which of the following symbol is used in Python for single line comment?
a)/
b) /*
c) //
d) #
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])
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
d. none of these
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
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
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:
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)
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
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)