Revision Notes
Revision Notes
Variables and data types: Variables are used to store data. Data types of variables:
● Numeric Types: int, float, complex
● Boolean – True or False values.
● None – a special type with an unidentified value or absence of value.
● Sequence: an ordered collection of elements. String, List and Tuples are sequences.
● Mappings – Dictionaries are mappings. Elements of dictionaries are key-value pairs.
Multiple Assignments:
• Assigning same value to multiple variables - a=b=c=1
• Different values to different variables- a, b, c = 5,10,20
print statement: used to display output. If variables are specified i.e., without quotes then value
contained in variable is displayed.
E.g., x = "kve " Output:
print(x) kve
To combine both text and a str variable, Python uses the “+” character:
Example
x = "awesome" Output:
print("Python is " + x) Python is awesome
Precedence of Operators: The operator having high priority is evaluated first compared to an
operator in lower order of precedence when used in an expression.
Examples:
1. x = 7 + 3 * 2 2. >>> 3+4*2
13 11
* has higher precedence than +, so it first Multiplication gets evaluated before the
multiplies 3*2 and then adds into 7 addition operation
Comments: Comments are ignored by the Python interpreter. Comments gives some message
to the Programmer. It can be used to document the code. Comments can be:
• Single-line comments: It begins with a hash(#) symbol and the whole line is considered
as a comment until the end of line.
• Multi line comment is useful when we need to comment on many lines. In python, triple
double quote (" " ") and single quote (' ' ') are used for multi-line commenting.
Example:
# This is a single line comment
' ' 'I am a multi
line comment ' ' '
input() function:An input() function is used to receive the input from the user through the
keyboard. Example: x=input('Enter your name')
age = int( input ('Enter your age'))
Selection Statements: It helps us to execute some statements based on whether the condition
is evaluated to True or False.
if statement: A decision is made based on the result of the comparison/condition. If condition is
True then statement(s) is executed otherwise not.
Syntax:
if <expression>:
statement(s)
Example:
a=3 Output:
if a > 2: 3 is greater
print(a, "is greater") done
print("done")
If-else statement:
If condition is True then if-block is executed otherwise else-block is executed.
Syntax:
if test expression:
Body of if stmts
else:
Body of else
Example:
a=int(input('enter the number')) Output:
if a>5: enter the number 2
print("a is greater") a is smaller than the input given
else:
print("a is smaller than the input given")
If-elif-else statement: The elif statement allows us to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions evaluates to TRUE.
Syntax:
If <test expression>:
Body of if stmts
elif < test expression>:
Body of elif stmts
else:
Body of else stmts
Example:
var = 100 Output:
if var == 200: 3 - Got a true expression value
print("1 - Got a true expression value") 100
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
While loop: while loop keeps iterating a block of code defined inside it until the desired
condition is met.
For loop: for loop iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects.
Syntax:
for <loopvariable> in <sequence>:
Statement(s)
Example 1: Output is:
L = [ 1, 2, 3, 4, 5] 12345
for var in L:
print( var, end=’ ‘)
Example 2: output: 0,1,2,3,4,5,6,7,8,9
for k in range(10):
print(k, end =’ , ‘)
List:Lists are ordered mutable data types enclosed in square brackets. E.g., [ 'A', 87, 23.5 ]
Python has a set of built-in methods that you can use on lists
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Tuples: A tuple is a collection which is ordered and unchangeable. In Python tuples are
created by enclosing items within round brackets. Tuple is immutable. We can create tuple in
different ways.
X=( ) # an empty tuple
X=(1,2,3) # a tuple with three elements
X=tuple(list1)
X=1,2,3,4
Accessing elements of a tuple:
We can use index to access the elements of a tuple. From left to right, index varies from 0 to n-
1, where n is total number of elements in the tuple. From right to left, the index starts with -1 and
the index of the leftmost element will be –n, where n is the number of elements.
T = ( 1, 2,4,6) Output:
print(T[0]) 1
print(T[-1]) 6
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key
with a value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys.
values() Return a new view of the dictionary's values
remove() It removes or pop the specific item of dictionary
del( ) Deletes a particular item
len( ) we use len() method to get the length of dictionary
10. Which point can be considered as difference between string and list?
a. Length c. Indexing and Slicing
b. Mutability d. Accessing individual elements
16. If D=1,2,3
What will be the data type of D?
a) List b)tuple c)set d)invalid type
20. Assertion(A):After adding element in a list, its memory location remains same
Reason(R):List is a mutable data type
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
Answers of MCQ:
1)a 2)a 3)b 4)a 5)d 6)c 7)a 8)b 9) d 10)b 11)b 12)b 13)a 14)c
15)c 16)b 17)c 18)a 19)b 20)a 21)c
5. How many times the following loop will execute? Justify your answer
A=0
while True:
print(A)
A =A+1
6. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
7. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
print(‘\n’, A)
18.Find output.
vowels=['a','e','i']
vowels.append('o')
vowels.append(['u'])
vowels.extend(['A','E'])
print("New List:",vowels)
19.Given the following declaration, what will be the output of the following:
Lst=(1,2,3,4,5)
del Lst[2]
print(Lst)
20.Identify the statement(s) from the following options which will raise TypeError exception.
a)print(‘5’*’3’)
b)print(5*3)
c)print(‘5’+3)
d)print(‘5’+’3’)
e)print(‘5’*3)
1)10
2)30
3)
*
* *
* * *
4) * * * * *
* ***
* * *
* *
*
5)infinite loop. Condition / test expression is always Ture.
6) 0,1,2,3,4,5,6,7,8,9
7) 0,1,2,3,4,5,6,7,8,9
10
10)TypeError
11) [1,2,3,4,5,6,7,8,9]
12) [1,2,3,4,5,6,7,8]
3. Create a list k, by selecting all the odd numbers within the given range, m and n. User will
input the values of m , n at run time
4. Write Python code to create and add items to a dictionary. Ask the user to input key value
pairs. Continue as long as the user wishes.
5. Write Python code to find whether the given item is present in the given list using for loop.
8. Mr. Rahul wants created a dictionary to store the details of his students and to
manipulate the data. He wrote a code in Python, help him to complete the code:
studentDict = # stmt 1
n = int(input("How Many Students you Want To Input?"))
for i in range( ): # stmt 2 - to enter n number of students data
rollno = input("Enter Roll No:")
name = input("Enter Name:")
physicsMarks = int(input("Enter Physics Marks:"))
chemistryMarks = int(input("Enter Chemistry Marks:"))
mathMarks = int(input("Enter Maths Marks:"))
studentDict[rollno]= # stmt 3
Answers /Hints: Short answer Type Questions.
1) for k in D.items():
print(k)
2) a =int(‘input the item to be deleted’)
l.remove(a)
3) m = int(input(‘lower limit’))
n = int(input(‘upper limit’))
n = n+1
L = [x for x in range(m, n) if x%2!=0]
4)D = { }
while True:
K = input(‘type a key’)
V = int(input(‘type the value’)
D[K] = V
C = input(‘type ‘y’ to add more’)
if C!=’y’:
break
5) flag = 0
L = eval(input(‘input a list on numbers’))
E = int(input(‘item to be searched’)
K =len(L)
for p in range(K):
if E ==L(p):
flag = 1
print(‘found and index is ‘,p)
if flag==0:
print(‘not found’)
6) list1=[]
for x in range(10):
list1.append(x**2)
list1
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
OR
list1=list(map(lambda x:x**2, range(10)))
7) L=eval(input("Enter a list"))
D={"ODD":[],"EVEN":[]}
for i in L:
if i%2!=0:
D["ODD"].append(i)
else:
D["EVEN"].append(i)
print(D)
8) Statement 1 : StudentDict = dict( )
Statement 2 = for i in range( n ):
Statement 3: studentDict[rollno]=[name, physicsMarks, chemistryMarks, mathMarks]