0% found this document useful (0 votes)
2 views49 pages

CH_Flow of Control, Lists, Dictionaries

The document explains control statements in Python, categorizing them into three types: sequential, selection (conditional), and iteration (looping) statements. It provides examples of each type, including simple and compound statements, as well as various conditional structures like if, if-else, and elif statements. Additionally, it covers the use of loops, specifically for and while loops, with practical coding examples for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views49 pages

CH_Flow of Control, Lists, Dictionaries

The document explains control statements in Python, categorizing them into three types: sequential, selection (conditional), and iteration (looping) statements. It provides examples of each type, including simple and compound statements, as well as various conditional structures like if, if-else, and elif statements. Additionally, it covers the use of loops, specifically for and while loops, with practical coding examples for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

CONTROL STATEMENTS

1. Statement:
 This is a line of code in program that instructs the computer.
 In python, there are 3-types of statements:
 Empty statement
 Empty statement means no statement.
 Empty statement represents in python using pass.
 Simple statement
 Simple statement means a single statement in python.
 Compound statement
 Compound statement means set of two/more statements as a block.
2. Control statements
These statements control the flow of execution of statements in a program.
In python, there are 3-types of control statements. They are:
(a) Sequential statements
(b) Selection/conditional statements
(c) Iteration/looping statements
(a) Sequential statements:
 In these all statements in a program will execute in sequential order, i.e. one after another.

Eg(1): Write a python program that takes principal amount, time and rate of interest from
console and calculate and display simple interest an output.
Hint: simpleinterest=p*t*r/100
#filename: simple_int.py

p=float(input('Enter principal ampount:'))


t=float(input('Enter time:'))
r=float(input('Enter rate of interest:'))
si=p*t*r/100
print('simple interest=',si)

Output:
Enter principal ampount:2000
Enter time:2
Enter rate of interest:12
simple interest= 480.0

Eg(2): Write a python program that takes radius of circle as input from console and calculate
and display area and perimeter of circle.
#filename: area_peri_circle.py
r=float(input('Enter radius of circle:'))
area=3.14*r*r
peri=2*3.14*r
print('area of circle=',area)
print('perimeter of circle=',peri)

Output:
Enter radius of circle:5.67
area of circle= 100.94754599999999
perimeter of circle= 35.6076

Eg(3): Write a python program that takes temperature in oC (Celsius) as an input and display in
Fahrenheit.
Hint: F=(C*9/5)+32
#filename: Celsius_Fahrenheit.py

c=float(input('Enter temperature in Celsius:'))


f=(c*9/5)+32
print('The given temerature in Faherenheit is=',f)

Output:
Enter temperature in Celsius:32
The given temerature in Faherenheit is= 89.6

(b) Selection/conditional statements


 The selection statements allow to choose the set-of-instructions for execution depending upon an
expression’s truth value.
 There are 4-types of selection statements in python
(i) if statement
(ii) if else statement
(iii) elif statement
(iv) nested if statement

(i) if statement
 It tells your program to execute a certain section of code only if a particular condition evaluates to
true.
Syntax:
if condition:
statement1
statement2
 In above syntax, if condition’s result is true then ‘statement1’ (if block) will execute otherwise
‘statement1’ will not executes.
 Irrespective of condition’s result ‘statement2’ will executes because it is outside of ‘if’ statement.

Representation of simple if syntax as flowchart

True
Condition1

Statement1
False

Statement2
Eg(1): Write a python program that takes amount from console and calculate and display final amount to
be paid based on the following condition.
Condition: if the given amount is more than 5000, then they will get 5% discount.

#Filename: simple_if_discount.py
amt=float(input('Enter Amount:'))
dis=0
if amt>5000:
dis=(amt*5)/100
famt=amt-dis
print('Final Amount to be paid is=',famt)

Output:
Enter Amount:7000
Final Amount to be paid is= 6650.0

Eg(2): What will be the output of following code fragment?


#filename: simple_if_output1.py
a=10
if a>5:
a+=15
a-=2
print('a value is=',a)

Output:
a value is= 23
Eg(3): What will be the output of following code fragment?
#filename: simple_if_output2.py
a=10
if a<5:
a+=15
a-=2
print('a value is=',a)

Output:
a value is= 10

Eg(4): What will be the output of following code fragment?


#filename: simple_if_output3.py
a=10
if a<5:
a+=15
a-=2
print('a value is=',a)

Output:
a value is= 8

(ii) if else statement


 The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to
false.
Syntax:
if condition:
statement1
else:
statement2
statement3

In above syntax, if condition’s result is true then ‘if block’ (‘statement1)’ will execute otherwise else block
(‘statement2’) will executes. After execution of either ‘if block’ or ‘else block’ then the statement that is
outside of ‘if-else’ (statement3) will execute.
Representation of if-else syntax as flowchart

False True
Condition1

Statement2 Statement1

Statement3

Eg(1): Write a python program that takes amount from console and calculate and display final amount to
be paid based on the following condition.
Condition: if the given amount 5000 or more, then they will get 10% discount otherwise 5%.
#filename: if_else_discount.py

amt=float(input('Enter Amount:'))
if amt>=5000:
dis=(amt*10)/100
else:
dis=(amt*5)/100
famt=amt-dis
print('Final Amount to be paid is=',famt)

Output1:
Enter Amount:7000
Final Amount to be paid is= 6300.0

Output2:
Enter Amount:3000
Final Amount to be paid is= 2850.0
Eg(2): ): Write a python program that takes number from console and display whether the given
number is posive or negative.
#filename: if_else_positive_negative.py
n=int(input('Enter Number:'))
if n>=0:
print('The given number',n,'is positive number')
else:
print('The given number',n,'is negative number')
Output1:
Enter Number:45
The given number 45 is positive number

Output2:
Enter Number:-45
The given number -45 is negative number
Eg(3): Write a python program that checks the given number is odd or even.
#filename: if_else_odd_even.py

n=int(input('Enter Number:'))
if n%2==0:
print('The given number',n,'is even')
else:
print('The given number',n,'is odd')

Output1:
Enter Number:54
The given number 54 is even

Output2:
Enter Number:45
The given number 45 is odd

(iii) elif statement


 Whenever we would like to check multiple conditions, in which at most only one condition is true, then
we can use elif statement.
 elif conditions will be evaluated from top to down.
 As soon as an if statement from the ladder evaluates to true, the statements associated with that
if are executed, and the remaining part of the ladder is bypassed.
 The last most else is executed only when no condition in the whole ladder returns true.
Syntax:
Syntax:
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
.
.
elif conditionn:
statementn
else:
statementm
statement(m+1)

Representation of elif syntax as flowchart

True False
Condition1

Statement1
True Condition2 False

Statement2
True False
Condition3

Statement3

.
.
.

True
Conditionn

Statementn Statementm

Statement(m+1)
Eg(1): Write a python program that find and display the respective day name based on the given
number. If the given number is not in range from 1 to 7 then display an error message as “invalid
input…please enter valid digit”.
#filename: elif_dayname.py

n=int(input('Enter digit in between 1 to 7:'))


if n==1:
print("dayname=Sunday")
elif n==2:
print("dayname=Monday")
elif n==3:
print("dayname=Tuesday")
elif n==4:
print("dayname=Wednesday")
elif n==5:
print("dayname=Thursday")
elif n==6:
print("dayname=Friday")
elif n==7:
print("dayname=Saturday")
else:
print("invalid input…please enter valid digit")

Output1:
Enter digit in between 1 to 7:5
dayname=Thursday

Output2:
Enter digit in between 1 to 7:9
invalid input…please enter valid digit

Eg(2): Write a python program that find and display the grade for three subject marks based on
the following criteria.

AvgMarks Grade
>=90 A+
<90 and >=80 A
<80 and >=70 B+
<70 and >=60 B
< 60 C
#Filename: elif_grade.py

m1=int(input('Enter marks in subject1:'))


m2=int(input('Enter marks in subject2:'))
m3=int(input('Enter marks in subject3:'))
avg=(m1+m2+m3)/3
if avg>=90:
print("Grade=A+")
elif avg>=80:
print("Grade=A")
elif avg>=70:
print("Grade=B+")
elif avg>=60:
print("Grade=B")
else:
print("Grade=C")

Output1:
Enter marks in subject1:55
Enter marks in subject2:65
Enter marks in subject3:75
Grade=B

Output2:
Enter marks in subject1:85
Enter marks in subject2:95
Enter marks in subject3:99
Grade=A+
Eg(3): Write a python program that calculates and display GST amount and final amount to be
paid based on the following data.
Hint: finalamount=givenamount+GST amount
Amount GST
>=10000 28%
<10000 and >=7500 18%
<7500 and >=5000 12%
<5000 5%

#Filename: elif_GST1.py
amt=int(input('Enter Amount:'))
if amt>=10000:
gst=(amt*28)/100
elif amt>=7500:
gst=(amt*18)/100
elif amt>=5000:
gst=(amt*12)/100
else:
gst=(amt*5)/100
final_amt=amt+gst
print('GST amount=',gst)
print('Final Amount to be paid=',final_amt)

Output1:
Enter Amount:12000
GST amount= 3360.0
Final Amount to be paid= 15360.0

Output2:
Enter Amount:4000
GST amount= 200.0
Final Amount to be paid= 4200.0
(iv) Nested if statement
The ‘if’ statement within the ‘if ’ statement called nested if statement.
Eg(1): Write a python program that takes three different numbers from console as input and find
the largest among these three numbers (using nested if statement).
#filename: nested_if_biggest_three.py

a=int(input('Enter number1:'))
b=int(input('Enter number2:'))
c=int(input('Enter number3:'))
if a>b:
if a>c:
L=a
else:
L=c
else:
if b>c:
L=b
else:
L=c
print('largest number among ',a,',',b,', and',c,'is=',L,sep='')
Output:
Enter number1:122
Enter number2:12
Enter number3:13
largest number among 122,12, and13is=122

(c) Iteration/looping statements


 These statements will execute again and again for specific number of times or until condition’s
result is False.
 In python, there are two types of loop. They are
(a) for loop (counting loop)
(b) while loop (conditional loop)
(a) for loop (counting loop)
 This is counting loop, i.e. this loop will execute for specific number of times.
Syntax:
for var in range/sequence:
#for body

 for loop will applied on range()/sequence.


range()
This is a pre-defined function which is used to get the values in ranges.
Syntax:
range(start,stop,step)

 start: Starting number of the sequence.


 stop: Generate numbers up to, but not including this number.
 step: Difference between each number in the sequence.
Note-1: All parameters must be integers (may be positive or negative).

Note-2: Atleast one parameter must be there in python. If there is only one
parameter, then it will be considered as ‘stop’ value. If there will be two
parameters, then these will be ‘start’ and ‘tart’ respectively.

Eg(1): range(6) generates the numbers from [0,1,2,3,4,5].

Eg(2): range(2,6) generates the numbers from [2,3,4,5].

Eg(3): range(2,10,2,) generates the numbers from [2,4,6,8].

Eg(4): range(1,10,2,) generates the numbers from [1,3,5,7,9].

Eg(5): range(10,1,-2,) generates the numbers from [10,8,6,4,2].


 If range() function will generate ‘n’ number of values, then the ‘for’ loop will
execute for ‘n’ times.
 In ‘for’ syntax, ‘var’ is the variable that takes the value of the item inside the sequence
on each iteration.

Flowchar for ‘for’ syntax:

For each item


Sequence /range

Last Item Yes


Reached?
No

Exit Loop

Statement1

Eg(1):
for i in range(1,6):
print(i)

Output:
1
2
3
4
5
Note: in above example, range generates numbers from ‘1’ upto ‘6’,but not including ‘6’.
Eg(2):
for i in range(1,6):
print(i,end=' ')

Output:
12345

Eg(3):
for i in range(6):
print(i,end=' ')
Output:
012345
Note: in above example, there is start value. The range will starts from 0(zero), if there is
no start value in range.

Eg(4):
for i in range(6,0,-1):
print(i,end=' ')

Output:
654321

Eg(5): Write a python program that displays the odd numbers and even numbers separately from
1 to given number.
#Filename: odd_even_nos.py

n=int(input('Enter number:'))
print('The Even Numbers Are:')
for i in range(2,n+1,2):
print(i,end=' ')
print('\nThe Odd Numbers Are:')
for i in range(1,n+1,2):
print(i,end=' ')

Output:
Enter number:10
The Even Numbers Are:
2 4 6 8 10
The Odd Numbers Are:
13579

Eg(6): Write a python program that find and displays the sum of natural numbers from 1 to given
number.
#Filename: sum_natual_nos.py

n=int(input('Enter number:'))
sum=0
for i in range(1,n+1):
sum+=i
print('The sum natural Nos=',sum)
Output:
Enter number:10
The sum natural Nos= 55
Eg(7): Write a python program that finds and displays the sum of odd and even numbers from 1
to given number.
#Filename: sum_odd_even_nos.py

n=int(input('Enter number:'))
sum1=0 #to store odd sum
sum2=0 #to store even sum
for i in range(1,n+1):
if i%2!=0: # here, checking whether 'i' value is odd or not
sum1+=i
else:
sum2+=i
print('The sum Odd Nos=',sum1)
print('The sum Even Nos=',sum2)

Output:
Enter number:10
The sum Odd Nos= 25
The sum Even Nos= 30
Eg(8): A simple python example that illustrates ‘for’ loop with sequence.

L=[10,20,30] #here, 'L' is a list


sum=0
for i in L:
sum+=i
print(sum)

Output:
60

Eg(9):
s='python' #here, 's' is a string
for i in s:
print(i)
Output:
p
y
t
h
o
n
Note: In above example, first ‘i’ value will be ‘p’, then ‘i’ value will be ‘y’ and so on..
(b) while loop (conditional loop)
This is conditional loop, i.e. the while loop will execute again and again until the condition’s result
is False.
Syntax:
while condition:
#whilebody

 Generally there will four steps in while loop. They are:


 Initialization expression (starting)
 Test Expression (Repeat/stop)
 While body (Doing/process of body)
 Update expression (changing)

Flowchart for “while” loop syntax

False
Condition1

True

While body

The statement that is outside of while loop


Eg(1):
n=int(input('Enter Number:'))
i=1
while i<=n:
print(i)
i+=1

Output:
Enter Number:5
1
2
3
4
5

Eg(2): Write a python program that find and displays the sum of natural numbers from 1 to given
number (using while loop).
#Filename: sum_natual_nos.py

n=int(input('Enter Number:'))
i=1
sum=0
while i<=n:
sum+=i
i+=1
print('Sum of natural Nos is:',sum)

Output:
Enter Number:10
Sum of natural Nos is: 55

Eg(3): Write a python program that find and displays the series of Fibonacci upto given value.
#Filename: Fibonacci_nos.py

n=int(input('Enter Number to print fibonacci series:'))


a=0
b=1
print('The fibonacci series is:')
print(a,end=' ')
c=a+b
while c<n:
print(c,end=' ')
c=a+b
a=b
b=c

Output:
Enter Number to print fibonacci series:100
The fibonacci series is:
0 1 1 2 3 5 8 13 21 34 55 89
3) Jumping Statements
There are two jumping statements in the loops of python. They are:
(a) break statement
(b) continue statement

(a) break statement


 It terminates the execution of the loop.
 Break can be used in while loop and for loop.
Flowchart of break

False
Condition1

True

Yes
break?

No
Remaining body
Exit Loop

Eg(1):
s='uselessfellow'
for i in s:
if i=='f':
break
else:
print(i)

Output:
u
s
e
l
e
s
s
Note: in above example, if ‘I’ value is ‘f’ then the ‘break’ will execute. That means, ‘for’ loop
execution will be aborted.

Eg(2):
a=10
for i in range(1,a+1):
if i==5:
break
else:
print(i)
print('hi')
print('EOP')

Output:
1
hi
2
hi
3
hi
4
hi
EOP
(b) continue statement
 The continue statement is used to skip the rest of the code inside a loop for the current iteration
only.
 Loop does not terminate but continues on with the next iteration.
Flowchart of continue

False
`Condition

True

Yes
continue

No
Remaining body

Exit Loop

Eg(1):
s='uselessfellow'
for i in s:
if i=='f':
continue
print('hello')
else:
print(i)

Output:
u
s
e
l
e
s
s
e
l
l
o
w
Note: In above example, if ‘i' value is ‘f’ then ‘continue’ will execute. Once ‘continue’ will execute
then print(‘hello’) doesn’t execute.
Eg(2): a=int(input('Enter number:'))
for i in range(1,a+1):
print('hi')
print('hello')
if i==2:
continue
print('uf')
print('bye')

Output:
Enter number:3
hi
hello
uf
bye
hi
hello
hi
hello
uf
bye

Note: In above example,


4) ‘else’ in loops
 We can use ‘else’ in ‘for’ or ‘while’ loops.
 ‘else’ part will executes in loops after successful completion of loop iterations.
 In case if loop will be aborted in middle of the execution, then ‘else’ doesn’t execute.

Eg(1):In the example, for loop ‘else’ part will execute, because ‘for’ will execute successfully.

s='python'
for i in s:
if i=='h':
pass
else:
print(i)
else:
print('End of the for loop::')

Output:
p
y
t
o
n
End of the for loop::

Eg(2): In the example, for loop ‘else’ part doesn’t execute, because ‘for’ loop execution will be
aborted when ‘i' value in ‘h’.

s='python'
for i in s:
if i=='h':
break;
else:
print(i)
else:
print('End of the for loop::')

Output:
p
y
t

Flowchart
 Flowchart is a pictorial representation of an algorithm to solve a problem.
 Symbols used in flowchart.

Start/Stop

Process

Condition / Decision

CONTROL STATEMENTS 59
Flow Control

Documentation

Connectors

Input/ Output

Eg(1): Write a Flowchart that finds addition of two given numbers:

Start

Read a
Read b

c=a+b

print c

Stop
Eg(2): Write a Flowchart that finds biggest among given two numbers:

Start

Read a
Read b

True False
a>b?

print a print b
is big is big

Stop

Pseudocode
The informal representation of steps to solve a problem is called pseudocode.
Eg(1): Write a pseudocode that finds biggest among given two numbers:
Sol:
Step1: start
Step2: read values into a and b
Step3: if a values is greater than b , then print a as an output, otherwise print ‘b’ as an output.
Step4: Stop

Decision Trees:
This is a tool that represent hierarchy of steps based on decisions.

Eg(1): Write a decision tree for the following problem.


The salesperson would like to deliver the food to house no.4 where there is sequence of houses
numbered from 1 to 10.
If houseNo!=4

False True

False True If houseNo!=4


Deliver food
False True

Deliver food If houseNo!=4

False True

Nested loop:
 The loop with in the loop is called nested loop.
 The nested loops are used to represent rows and columns.
 The outer loop represents number of rows and the inner loop represent number of columns.
Eg (1): Write a python program that prints the pattern as follows.
1
22
333
4444
55555
666666
7777777
88888888
999999999
Solution:
Note: In the given problem, there are 9 rows. That’s why outer loop should execute for 9 times.
In first iteration one 1 should be printed, in second iteration two 2’s , 3rd iteration three 3’s
…should be printed. That’s why the inner loop should execute from 1 to iteration number
of times.
for i in range(1,10):
for j in range(1,i+1):
print(i,end='')
print()

Eg (2): Write a python program that prints the pattern as follows.


999999999
88888888
7777777
666666
55555
4444
333
22
1
Solution
for i in range(9,0,-1):
for j in range(i,0,-1):
print(i,end='')
print()
Eg (3): Write a python program that prints the pattern as follows.
1
12
123
1234
12345
123456
1234567
12345678
123456789
Solution:
for i in range(1,10):
for j in range(1,i+1):
print(j,end='')
print()
Eg (2): Write a python program that prints the pattern as follows.

123456789
12345678
1234567
123456
12345
1234
123
12
1
Solution:
for i in range(9,0,-1):
for j in range(1,i+1):
print(j,end='')
print()

SAMPLE QUESTIONS

1. Write a program that lets the user enter a number. Then the program displays
the multiplication table for that number from 1 to 10. E.g., when the user enters 12,
the first line printed is “1 * 12 = 12” and the last line printed is “10 * 12 = 120”.

2. What is printed by the Python codes?


a) for z in [2, 4, 7, 9]: b) n=3 c)
print(z - 1) for x in [2, 5, 8]:
n=n+x
print(n)
3. The following code displays a message(s) about the acidity of a solution:
ph = float(input("Enter the ph level: "))
if ph < 7.0:
print("It's acidic!")
elif ph < 4.0:
print("It's a strong acid!")
a. What message(s) are displayed when the user enters 6.4?
b. What message(s) are displayed when the user enters 3.6?
c. Make a small change to one line of the code so that both messages are displayed when a value
less than 4 is entered.

4. Rewrite the following codes using for loop


(a) i=100 b) while(num>0):
while (i>0): print(num%10)
print(i) num=num/10
i-=3
5. Write a python program that finds factorial of given number?
6. Under what condition the following code will print “hi”.
if(x<10):
print(‘hello’)
elif(x<100):
print(‘hi’)
else:
print(‘see..you’)
7. What is the output of the following?
i=1
while True:
if i%3==0:
break;
print(i)
i+=1
8. Write flowchart, pseudocode and decision tree for the following problem.
Printing odd numbers from 1 to 10.
9. n= int(input("enter a number:"))
i=2
while n > 1 :
while n % i == 0 :
print(i, end = " ")
n //= i
i += 1
print()

Find the output for the following inputs.


i) 54
ii) 24
What does the program do?

10. Write a program to generate the following pattern for a given value of n.
If n = 4, then the expected output is:
4444
4333
4322
4321

11. What will be the output after the following code is executed?
(a) for I in range(1,5,-1): b) for I in range(5,1,-1):
print(i+1,end=’ ‘) print(i+1,end=’ ‘)
i=i+1 i=i+1
12. Define the following.
(a) Flowchart (b) decision tree (c) pseudocode
LISTS
1) List
 This is ordered collection of items of any type enclosed in square brackets.
 The list items are separated by comma.
2) Creating Lists
The list can created in many ways.
2.i. creating empty list
L1=[ ]
(or)
L1=list()
2.ii. creating list with values
L1 = [11, 20, 30]
L2 = *1,’hi’, 2.5, 5+6j+
Note: List can have any type of values.

 The list items are identified by using indexes.


 Every item in the list has its own index value. No two items should be same.
 The index values may be either positive or negative integers.
 Positive Indexes are used to visit the list from left to right. (i.e. from beginning to ending)
 Positive indexes will starts from 0 (zero),1,2,…..
 Negative Indexes are used to visit the list from right to left. (i.e. from ending to beginning)
 Negative indexes will starts from -1,-2,-3,…...
Eg: >>>L1=[11,33,9,23,45,99]

 Now, List L1 has positive indexes from 0 to 5 and negative indexes from -1 to -6 as shown below.

 We can access list items by using their index values.


 Syntax to access list elements
Listname[index]
Eg:
 If we try to access an element whose index is not in given list, then IndexError will come.
Eg(1):

Note: In above example, we tried to access an element whose index is ‘6’ in list ‘L1’. But there is
no index called ‘6’ in L1.

 Lists are mutable, means we can change list items.


Eg(1):

Note: In above example, L1*2+ value was ‘33’. Later we changed to 99.

3) Membership operators on Lists


 Membership operators (in and not in) can be applied on list.
 If the given item is in list, then in will return True, otherwise it will return False.

Eg:

4) Concatenation (+) and replication (*) operators on Lists


 Concatenation operator is used to join two lists.
 Replication operator is used to repeat the list for given number of times.
Eg(1):

Note: In above example, list ‘L2’ added at the end of list ‘L1’ in the output only. But, there will be
no change original L1 and L2.
Eg(2):

Note: In above example, list ‘L2’ repeated thrice only in the output. Original L2 will [1,2,3] only.

 Whenever we are replicating the lists, one operand should be ‘list’ and other operand must be
number, otherwise it will give “TypeError”.
Eg(1) :

Note: In above example, we tried to replicate list ‘L1’ with string ‘3’. That’s why we got
‘TypeError’.
Eg(2):

Note: In above example, we tried to replicate list ‘L1’ with list ‘L2’. That’s why we got
‘TypeError’.

5) Lists slicing
 Extracting sub-list from the given main list is called list slice.
Syntax:
String_name [beginning: end: step]
 beginning represents the starting index of string
 end denotes the end index of string which is not inclusive
 Steps denotes the distance between the two list items.
Eg(1):

Note: In above example, the sub list will starts from 1st index upto 5th index (but not
including 5th (including 4th index) index).
Eg (2):

Note: In above example, the sub list will starts from 1st index upto end of the list.

Eg (3):

Note: In above example, the sub list will starts from 0th index upto 5th index (but not
including 5th (including 4th index) index).

Eg (4):

Eg (5):

Note: In above example, the list ‘L1’ will be reversed in the output only. But, in the original list ‘L1’
there will be no change.

Eg (6):

Note: In above example, the list ‘L1’ will be reversed and the sub list will be every second
character starts from first element.
6) List Methods
 Python provides some basic methods to manipulate lists.
 List methods can be accessed by using the following syntax.
Syntax:
List.methodname()
6.i. append()
 The append() method adds a single item to the existing list.
 It doesn't return a new list; rather it modifies the original list.

Syntax:
listname.append(item)

Eg (1):

Note: in above example, we added ‘66’ to list ‘L1’ in the end.

Eg (2): The following example will give error , because we can’t add two values using append
method into a list.

6.ii. extend()
 This is used to add two/more elements(as list) into a list.
Syntax:
list1.extend(list2)

Eg (1):

Note: In above example, we added two elements called 77,88 as a list into a list called ‘L1’.

Eg (2): The following example will give TypeError, because we haven’t given two elements as
list.
6.iii. insert()
 The insert() method inserts the element to the list at the given index.
Syntax:
listname.insert(index, element)

Eg(1):

Note: in the above example, an element ‘77’ inserted in 2nd indexed position.

Eg(2): In the following example, the element called ‘77’ inserted into 4th indexed place instead of
6th indexed place. Because in ‘L1’ max index value is ‘3’.

6.iv. index()
 index() method finds the given element in a list and returns its position.
Syntax:
list.index(element)

Eg:

 However, if the same element is present more than once, index() method returns its
smallest/first position.
Eg:

Note: in above example, element ‘33’ repeated two times in list ‘L1’.But index() will give index
of first occurrence.
 In case, if the given element is not list, then it will return ”ValueError”.

Eg:

6.v. count()
 count() method counts how many times an element has occurred in a list and returns it.
Syntax
listname.count(element)
Eg:

6.vi. pop()
 The pop() method removes and returns the element at the given index.
 pop() method will come with/without parameter.
Syntax
listname.pop(index)

 pop() without parameter will return and delete last element from the list.
Eg:

 pop() with parameter will return and delete element from the given index.
Eg:

Note: In above example, we passed ‘4’ as a parameter to pop() method, that’s why 4 th indexed
item has been deleted.
 pop() will return ‘IndexError’ if given index is not in list.
Eg:

6.vii. remove()
 The remove() method searches for the given element in the list and removes the first
matching element.
Syntax
listname.remove(element)

Eg:

 The remove() method will give ‘ValueError’ if given element is not in the list.
Eg:

Note: The main difference in between ‘pop’ and ‘remove’ is, ‘pop’ will display the item
before deleting the same, whereas ‘remove’ doesn’t.

6.viii. clear()
 The clear() method removes all items from the list.
 The clear() method doesn't take any parameters.
Syntax:
listname.clear()
Eg:

6.ix. reverse()
 The reverse() method reverses the elements of a given list.
 The reverse() function doesn't take any argument.
 The reverse() function doesn't return any value. It only reverses the elements and updates the
list.
Syntax:
listname.reverse()

Eg:

6.x. sort()
 The sort() method sorts the elements of a given list in a specific order - Ascending or
Descending.
Syntax (To sort in ascending order):
Listname.sort()
(or)
Listname.sort(reverse=False)
Eg:

Syntax (To sort in descending order):


Listname.sort(reverse=True)
Eg:
7) List Functions

 Python has some built-in aggregate functions like:


i. min()
ii. max()
iii. sum()
iv. len()
7.i. min()
 This is used to find smallest element in the list.
Eg:

7.ii. max()
 This is used to find largest element in the list.
Eg:

7.iii. sum()
 This is used to find total sum of all the elements in the list.
Eg:

Note: sum() function can be applied only on numbers but not on strings.

7.iv. len()
 This is used to find the number of elements in the list.
Eg:

8. List comparisons
 The comparison operators (<, <=, >, >=, ==, and !=)will perform same operation on lists, strings
and tuples.
 The lists can be compared if they are representing the same type of values, otherwise
“TypeError” will come.
Eg (1):
Note: in above example, the lists L1 and L2 are representing different type of items.

Eg (2):

Note: in above example, in list L1 and list L2 first item is same, that’s why it compare with
second item(i.e. 2<3 which is False).

SAMPLE QUESTIONS
1. Suppose you are given a list of words, wordList. Write Python code that will write one line for each
word, repeating that word twice. For example if wordList is ['Jose', 'Sue', 'Ivan'], then your code would
print
Jose Jose
Sue Sue
Ivan Ivan
2. Create a list that contains the names of 5 students of your class. (Do not ask for input to do so)
(i) Print the list
(ii) Ask the user to input one name and append it to the list
(iii) Print the list
(iv) Ask user to input a number. Print the name that has the number as index (Generate error
message if the number provided is more than last index value).
(v) Add “Kamal” and “Sanjana” at the beginning of the list by using “+”.
(vi) Print the list
(vii) Ask the user to type a name. Check whether that name is in the list. If exist, delete the name,
otherwise append it at the end of the list.
3. Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where
the its element is the sum of the first i+1 elements from the original list. For example, the cumulative
sum of [1, 2, 3] is [1, 3, 6].
4. Write a python program that search display the index of given element.
5. Write the most appropriate list method to perform the following tasks.
(a) Delete a given element from the list.
(b) Delete third element from the list.
(c) Add an element in end of the list.
(e) Add an element in beginning of the list.
(f) add elements of a list in the end of list.
6. Find the type of errors in the following code(s).
(a) L1=[11,22,33] (b) L1=[11,22,33] (c) L1=[11,22,33]
L1.pop(4) L1.remove(35) print(L1*3.0)
7. What is the difference in between the following, if ‘L1’ is *11,22,33+?
(a) L1*3
L1*=3
8. Write a function that takes in two sorted lists and merges them. The lists may not be of same length
and one or both may be empty.
9. Write a python program that ask the user to enter a list containing numbers between 1 and 12. Then
replace all of the entries in the list that are greater than 10 with 10.
DICTIONARIES
1) Dictionary
This is unordered collection of items in the form of key:value pair.
 Dictionaries are mutable, i.e. we can change dictionary items.
 A dictionary is like a list, but in a list, index value is an integer, while in a dictionary index value can be
any other data type and are called keys.
 Dictionaries are represented in curly brackets, i.e. {}
 Dictionaries are also called as associated arrays or mapping or hashes.

Syntax to create dictionary


dict_name={key1:value1,key2:value2,…….}

Note: the ‘key’ in dictionary must be immutable value, i.e. the key may be either string or
number or tuple.
Eg:
ITEM1 ITEM2 ITEM3

KEY1 KEY2 KEY1


VALUE1 VALUE2 VALUE1

2) Characteristics of Dictionaries
 Dictionary is unordered collection of items.
 Dictionary is not a sequence.
 Dictionary values are identified by keys not by indexes.
 Keys in dictionary must be unique.
 Dictionaries are mutable.
 Dictionaries internally stored as mappings.

3) Creating Dictionaries
3.i. Creating empty dictionary:
 The empty dictionaries will be created by using {} or dict() function.
Eg:

(or)
3.ii. Adding empty dictionary:
 We can add key:value pairs to empty dictionaries as follows.
Eg:

Note: In above example, first we created an empty dictionary called ‘d’ and then we added
one pair, i.e. 1 as key and ‘ICON’ as its value.
3.iii. Initializing a dictionary:
 Writing key: value pairs into dictionary at the time of its creation.
Eg:

3.iv. Creating a dictionary from lists:


 In this each should contain exactly two items. The first item will be considered as key and
second item as its value.
Eg:

3.v. Creating a dictionary using zip() function:


 In this, zip() function accepts two tuples as two parameters.
 The first tuple will acts as keys.
 The second tuple will acts as values.
Eg:

4) Accessing values from Dictionaries


 We can access values of a dictionary by using its key.
Eg (1):

Note: In above example, there is a key called 2 in dictionary ‘d’, that’s why we got
respective value as output.
Eg (2):

Note: In above example, there is no key called 20 in the dictionary ‘d’ , so we got
‘KeyError’.

5) Changing Dictionaries
 Dictionaries are mutable, so we can change dictionaries.
Eg:
 In the following example, d*2+ value is ‘MEDICON’.

 Now we would like to change d*2+ value to ‘MPL’. This can done as follows.

6) Membership operators on Dictionaries


 The membership operators in and not in can be applied on dictionaries, but they can check for
the existence of key only.
Eg (1):

Note: in above example, dictionary ‘d’ has a key called 2, that’s why answer is True.

Eg (2):

Note: in above example, in dictionary ‘d’ there is no key called 2, that’s why answer is
False.
7) Dictionaries Methods
The syntax to apply method on dictionaries is as follows.
Syntax
dictionaryname.methodname()
7.i. keys()
 The keys() method returns a view object that displays a list of all the keys in the dictionary.
 The keys() doesn't take any parameters.

Syntax:
dictionaryname.kesy()

Eg:

7.ii. values()
 The values() method returns a view object that displays a list of all the values in the
dictionary.
 The values() method doesn't take any parameters.

Syntax:
dictionaryname.values()

Eg:

7.iii. items()
 The items() method returns a view object that displays a list of dictionary's (key, value)
tuple pairs.
 The items() method doesn't take any parameters.

Syntax:
dictionaryname.items()

Eg:
7.iv. pop()
 The pop() method removes and returns an element from a dictionary having the given key.
 pop() method will one parameter.

Syntax:
dictionaryname.pop(key)

Eg (1):

Note: In above example, we deleted an item whose key is 2 from dictionary ‘d’.

Eg (2):

Note: In above example, we tried to delete an item whose key is 20 from dictionary ‘d, but that
key doesn’t exists. That’s key we got ‘KeyError’.

7.v. clear()
 The clear() method removes all items from the dictionary.
 The clear() method doesn't take any parameters.

Syntax:
dictionaryname.clear()
Eg:
7.vi. get()
 The get() method returns the value for the specified key if key is in dictionary.

Syntax:
dict.get(key, value)

 The get() method takes maximum of two parameters:


 key - key to be searched in the dictionary.
 value (optional) - Value to be returned if the key is not found. The default value is
None.
Eg (1):

Note: In above example, there is a key called 3, so we got its value ‘CT’ as output.

Eg(2):

Note: In above example, there is no key called 30 in dictionary, but didn’t get any error. Because,
get() method doesn’t return any error if key is not exists by default.

Eg(3):

Note: In above example, we wrote second parameter as ‘Key Doesnot Exists’ in get() method,
that’s why in output we got ‘Key Doesnot Exists’, because key 30 is not in ‘d’.

7.vii. update()
 The update() method updates the dictionary with the elements from the another
dictionary object.
 The update() method adds element(s) to the dictionary if the key is not in the dictionary.
 If the key is in the dictionary, it updates the key with the new value.
Eg (1):
Note: in above example, ‘d1’ and ‘d2’ has same key called 1, so ‘d1’ key 1 value will be
changed to ‘d2’ key 1 value, i.e. from ‘ICON’ to ‘IPL’ .

Eg (2):

Note: in above example, ‘d1’ and ‘d2’ has same key called 1, so ‘d2’ key 1 value will be
changed to ‘d1’ key 1 value, i.e. from ‘IPL’ to ‘ICON’.
8) Dictionaries Functions
There are few functions which can be applied on dictionary like list functions. They are:
i. min()
This will return minimum key from the dictionary.
ii. max()
This will return maximum key from the dictionary.
iii. sum()
This will return total key from the dictionary.
iv. len()
This will return number of items in the dictionary.

Note: min(), max() and sum() will work on keys of dictionaries only. The keys must be numbers,
otherwise we can’t apply min(), max(0, and sum(0 functions.

Eg (1):

Eg(2):
Note: In above example, one of the key value is string (‘3’). Sum(0, min(), and max() can’t be applied on
non-numericals, that’s why ‘TypeError’ has come.

Eg (3):

Problem-1
Given the dictionary d1={1:'ICON',2:'MEDICON',3:'CT'}, create a dictionary with the opposite mapping,
i.e. write a program to create the dictionary as: d1={'ICON':1,'MEDICON':2,'CT':3}

Solution:

Problem-2
Write a program that repeatedly asks the user to enter product name and prices. Store all of these in a
dictionary whose keys are the product names and whose values are the prices.
When the user done entering products and prices, allow them to repeatedly enter a product name and
print the corresponding price or message if the product not in the dictionary.

Solution:
ch='y'
d={}
while ch=='y' or ch=='Y':
name=input('enter name of the product:') #loading name
price=float(input('enter price of the product:')) #loading price
d[name]=price #adding key:value into dictionary
ch=input('To enter one more ..press y:')
ch='y'
while ch=='y' or ch=='Y':
name=input('enter name of the product:') #loading name
v=d.get(name,'product doesnot exists')
print('price=',v)
ch=input('To continue ..press y:')

Output:
enter name of the product:soap
enter price of the product:10
To enter one more ..press y:y
enter name of the product:shampoo
enter price of the product:15
To enter one more ..press y:Y
enter name of the product:paste
enter price of the product:20
To enter one more ..press y:n
enter name of the product:paste
price= 20.0
To continue ..press y:y
enter name of the product:brush
price= product doesnot exists
To continue ..press y:

SAMPLE QUESTIONS
1. Write a Python script to check if a given key already exists in a dictionary?
2. Write a Python program to iterate over dictionaries using for loops.
3. Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in
the form (x, x*x).
Sample Dictionary ( n = 5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
4. Write the output for the following codes.
A={10:1000,20:2000,30:3000,40:4000,50:5000}
print(A.items())
print(A.keys())
print(A.values())
5. Write a code to input ‘n’ number of subject and head of the department and also
display all information on the output screen.
6. Predict output for the following code.
d={}
d*1+=’Hello’
d*2+=’hi’
d*3+=’bye’
print(d)
7. Predict output for the following code.

weekdays = {'fri': 5, 'tue': 2, 'wed': 3, 'sat': 6, 'thu': 4, 'mon': 1, 'sun': 0}


print('fri' in weekdays)
print('thu' not in weekdays)
print('mon' in weekdays)

8. Predict output for the following code.


test = {1:'A', 2:'B', 3:'C'}
test.pop(1)
test[1] = 'D'
test.pop(2)
print(len(test))

You might also like