0% found this document useful (0 votes)
10 views69 pages

Chapter 5

Chapter 5 provides a comprehensive manual on looping statements in Python, covering concepts such as iteration, types of loops (finite, infinite, definite, indefinite), and control statements. It explains the functionality of various loop constructs, including while and for loops, as well as built-in looping functions and their syntax. Additionally, it discusses control statements like break, continue, and pass, along with practical examples and comparisons between different loop types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views69 pages

Chapter 5

Chapter 5 provides a comprehensive manual on looping statements in Python, covering concepts such as iteration, types of loops (finite, infinite, definite, indefinite), and control statements. It explains the functionality of various loop constructs, including while and for loops, as well as built-in looping functions and their syntax. Additionally, it discusses control statements like break, continue, and pass, along with practical examples and comparisons between different loop types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Chapter 5 -Manual

Manual for Looping Statements

CONCEPTUAL QUESTIONS

1. What is meant by looping or iteration?

Answer A set of instructions are repeated in the context of programming. This repetitive
execution of a set of instructions or groups of statements is termed looping,
iteration, or looping the loop.

2. What are the benefits of using the iterations or loops in Python?

A set of instructions are repeated in the context of programming.


The benefits of using loops in Python are as follows:
1. Loops aid in escalating the code reusability.
2. Loops simplify complex problems into simple ones which are very easy to
handle.
3. Loops aid in easily crisscrossing the elements placed in arrays and linked
lists.
4. Loops aid the developers, remove the drudgery of physical writing and
implement the upfront and petite instructions repetitively.

3. Explain the notion of a counter and a conditional loop?

Answer  Count-controlled loops- A construction for repeating a loop a certain


number of times. The Count-controlled loop in Python is the For Loop.
 Condition-controlled loop -A loop will be repeated until a given condition
changes. While loops possess this behaviour.

4. What are finite and infinite loops? Explain the differences between finite and
infinite loops.

Answer The quantity of iterations is limited in finite loops. The quantity of iterations is
unlimited in infinite loops.
Finite loops : It loops for a fixed amount of times.
Infinite loops : Indefinitely, it repeats the process. In Python, an infinite loop is a
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
conditional loop that executes over and over again until a stopping condition is
met, such as the runtime running out of memory or encountering an error.
There are many varieties of infinite loops in Python, including:
while statement.
if statement.
break statement.
continue statement.
An infinite loop always repeats itself without ever

5. What are definite and indefinite loops?

Answer The finite loops can further be typified as definite loops and indefinite loops. The
number of iterations is clearly defined in a definite loop. The number of iterations
is not clearly defined in an indefinite loop.

6. Distinguish between closed and open loops.

Answer An open-loop control system is one in which the input or controlling action is not
dependent on the output.

With closed-loop control, the input or controlling action is based on the outcome.

7. How do loops work, and what are entry-controlled and exit-controlled loops?

Answer The constructs in an indefinite loop, can be further subdivided into pre-test loops
or pre-checking loops or entry-controlled Loops and post-test loops or post-
checking loops or exit controlled Loops.

8. What are built-in functions and built-in looping functions? Why do we need
built-in looping functions?

Answer It is a function is a building block / or an element in programming language. It is a


collection of statements. It can be reused more than once in a program. The
functions enhance the comprehensibility, quality of the program, and it lowers the
cost for development and maintenance of the software.

The Inbuilt Functions looping through an iterable deprived of the use of a for loop
or while loop is known as the Inbuilt Looping Functions.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


The Inbuilt Looping Functions aid in looping through an iterable deprived of the
use of for loop or while loop. You can print the elements of the iterable deprived of
altering the actual elements of the iterable. They decrease the effort in coding as
they are easy and simple to use. By using these Inbuilt Looping Functions one can
write concise codes.

9. What are range functions? Why do we need the range functions?

Answer The built-in function range () is a function that is used to repeat over a sequence of
numbers.

It can create an iterator of arithmetic progressions.

10. Give the syntax for the range function? Name the parameters inside the range
function?

Answer Syntax:
range(stop) or range(start, stop[, step])

Parameters inside the range function start, stop, and step.

11. Outline the logic of a while loop with a flow chart

Answer The flow of execution for a while statement is as follows:

[i] While statement (loop) is activated with while keyword


[ii] Assess the test condition, to see if it yields True or False.
[iii] If the condition is true, execute the body containing the code and then go
back to step 1.
[iv] If the condition is false, skip the body containing the code following the
while statement
[v] If false, execute the succeeding statements in the rest of the program(like the
else block).
[vi] Loops until it reaches the end of the body; returns to the while statement
(containing the condition), re-examines the test condition and updates it.
Updates meaning is if it is true, repeats the execution of the body of the loop
until the process is over and until the condition fails or it becomes false.(note
- If true, and after execution of the body of the loop).If the condition is false,
you can go to the else block and execute the statements.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Figure 1: Flow Control of the While Loop With The Else Part

12. Give the syntax for (a) while loop,(b) for loop,(c) jump statements.

Answer (a). while loops


while condition:
Body of while loop

Syntax for while else loops


while condition:
Body of while loop
else:
Body of else

(b). for loop

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


(c)jump statements

13. “The "Python While Loop" is a condition-based iteration structure. Explain

Answer Python While Loop is called a condition-controlled loop.This type of looping


supports repeated execution of a statement or block of statements that is controlled
by a conditional expression. The while construct will keep performing a block as
long as a particular condition is true. The While Loop is usually picked up to
perform a task indeterminately, till a specific condition is satisfied.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


14. Explain the flow of execution for a while else loop?

Answer

Figure 2-Flow Control depicting the working of a While Loop With Else

15. What form will the while loop and the other component take?

Answer The while construct will keep performing a block as long as a particular condition
is true. The While Loop is picked up to perform a task indeterminately, till a
specific condition is satisfied.

16. Compare the for loop and while loop

Answer BASIS FOR


FOR WHILE
COMPARISON
Statement initialization while condition:
for condition:
iteration statements; //body of loop
//body of 'for' loop iteration
How the The top of the loop The top of the loop
statement is comprises of the comprises the
arranged  Initialization,  initialization
 condition checking,  condition checking.
 iteration statement.
Iteration It is written at the top, It can be written in any
statement hence, executes only after place in the loop.
all statements in the loop
are executed.
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
Use used when you have prior used when you have no
knowledge of the number prior knowledge of the
of iterations. number of iterations or it is
number is not correctly
known.
Condition without condition, the loop Throws a compilation
iterates infinite times. error when the condition is
not given.
Initialization done once only and is not done in condition
repeated. checking, and done every
time the loop is reiterated.

17. What is the logic behind a for else loop, and how does it work?

Answer [i] The for-keyword triggers a for statement (loop). Invoke the membership
expression and then require the result from the iterable (which is a
collection of elements).
[ii] The for loop's body will not be executed if the iterable is empty.
[iii] If the iterable did yield an element, allot that element to <var> .
o If <var> was not previously delineated, it becomes delineated).
[iv] Implement the bounded body of code, equal to the number of items or
elements in the collection.
[v] Return to the first line.

18. Write the syntax for nested while and for loops.
Answer
for [first iterating variable] in [do something] # Optional
[outer loop]:
while first condition:
[do something] # Optional
# Outer loop
[do something] # Optional while second condition:
for [second iterating variable] [do something] # Optional
in [nested loop]: # Nested loop
[do something]

19. Why do we need nested loops in a program?

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Answer In python, when a loop lies within or inside the body of another loop, it is called a
nested loop. The loop lying within another loop is called the inner loop and the
loop outer to the inner one is called the outer loop.

Nested loops are used to deal when there are too many iterations. It helps to reduce
the usage of memory size.

20. With the help of a flow chart, explain the working of a Break statement.

Answer

Figure 3-Flow Control depicting the working of a break

21. What are control statements?

Answer Python offers loop control statements, to alter the process of code execution of the
recursion statements. They provide the programmers with more flexibility in
designing the control logic of the loops. Python supports the control statements
like break, pass and continue.

22. What's the Break statement's purpose?

Answer The break statement is used in a sequential search(like searching for an element in
a list) using a for a loop. When an element is reached, in a sequential search, it
exits the loop deprived of passing through the residual elements. A break statement
is a deliberate stoppage to prohibit a loop from running. The break statement is
often used to dismiss the processing of codes. The break statement eradicates and
directs the flow of control in the code. The code implementation simply continues
to the next case, deprived of the break statement. Once inside a loop, and the code

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


bumps into it, it gets halted, the loop is immediately terminated and the program
control resumes at the next statement following the loop.

23. Show the functionality of a continue statement with a flowchart.

Answer

Figure 4-Flow Control depicting the working of a continue statement

24. Give an overview of how a pass statement operates using a flowchart.

Answer

Figure 5-Flow Control depicting the working of a Pass

When the specified condition in a loop (while or for) is true, followed by a pass
statement; then the value or repetition of the loop is done and proceeds onto the
subsequent line of code. It thus transfers the control to the start of the loop.

25. Is a pass statement really necessary?

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Answer The Pass statement is typically used when there is no requirement for a code, but a
statement is by itself or is still vital to write the code syntactically precise for
running. The pass statement is useful to construct a body, in places where there is
a necessity to ignore a code execution and nothing is to be performed inside the
block of code.

26. Bring out the differences between the Pass and the Continue statements

Answer Differences between Pass and Continue statement


BASED ON Pass statement Continue statement
Nature Of A null statement Not a null statement
Statement
Placeholder Can be used as a Cannot be used as a
placeholder for future placeholder for future code
code
Ensuing A pass, statement The Continue statement jumps
Development informs the interpreter to the topmost line of the loop.
Of Action regarding the non-
availability of code.
Forces Into A pass, the statement The Continue statement will
then passes the force the loop to start the
implementation to the succeeding iteration and
next statement or it tries complete it till the end.
to construe the ensuing
line of code.
Action It does not perform Preforms action by jumping to
Performe or stays doing the subsequent iteration
d nothing
Obligatory mandatory when mandatory when we want to
syntactically needed but skip the execution of remote
practically not inning statement(s) inside the
loop for the current iteration
Nature of the pass keyword is a "no- continue keyword, is used to

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Keyword operation" keyword resume a loop at the control
point
Example (i) Example (i): Example (i):
if reply == "yes": for i in range(99):
pass # add "yes" code if i % 2 == 0:
later. continue
print(i)
Example (ii) Example (ii): Example (ii):
nums = [111, 123, 965, nums = [111, 123, 965, 654,
654, 505] 505]
print("----Using print("----Using
\"pass\"-------") \"continue\"-------")
for n in nums: for n in nums:
if n == 2: if n == 2:
pass continue
print(n) print(n)

TRY-OUT QUESTIONS

Write the output of the following code

1. cricket_stadium_tickets = 0
while cricket_stadium_tickets <9:
print("Within Range")
cricket_stadium_tickets = cricket_stadium_tickets +3
else:
print("Out of Range")

Answe >>> cricket_stadium_tickets = 0


r >>> while cricket_stadium_tickets <9:
... print("Within Range")
... cricket_stadium_tickets = cricket_stadium_tickets +3
... else:
... print("Out of Range")
...
Within Range

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Within Range
Within Range
Out of Range

2. chickens_hatched=0
while chickens_hatched< 6:
chickens_hatched+=1
if chickens_hatched== 9:
continue
print(chickens_hatched )

Answe >>> chickens_hatched=0


r >>> while chickens_hatched< 6:
... chickens_hatched+=1
... if chickens_hatched== 9:
... continue
... print(chickens_hatched )
...
1
2
3
4
5
6

3. avocado=6
papya=9
while papya <12:
avocado=papya-1
papya=2*papya-avocado
print(papya,avocado)

Answe >>> avocado=6


r >>> papya=9

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


>>> while papya <12:
... avocado=papya-1
... papya=2*papya-avocado
... print(papya,avocado)
...
10 8
11 9
12 10

4. for x in range(6,65,10):
print(x)

Answe >>> for x in range(6,65,10):


r ... print(x)
...
6
16
26
36
46
56

5. for x in range(2,10,2):
print(x*"Python")

Answe >>> for x in range(2,10,2):


r ... print(x*"Python")
...
PythonPython
PythonPythonPythonPython
PythonPythonPythonPythonPythonPython
PythonPythonPythonPythonPythonPythonPythonPython

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


6. while True:
IMEI_no=input("Type in your IMEI:")
if len(IMEI_no)==8:
break
print("Your ID is"+IMEI_no)

Answe >>> while True:


r ... IMEI_no=input("Type in your IMEI:")
... if len(IMEI_no)==8:
... break
... print("Your ID is"+IMEI_no)
...
Type in your IMEI:I245LM8645
Your ID isI245LM8645
Type in your IMEI:LMK256
Your ID isLMK256
Type in your IMEI:LMK2LMK2

7. i=0
while i<=8:
i+=1
if i == 5:
continue
print(i)

Answe >>> i=0


r >>> while i<=8:
... i+=1
... if i == 5:
... continue
... print(i)
...
1
2
3
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
4
6
7
8
9
>>>

8. for i in [16,27,1281,494,74,75]:
if(i>=128):
pass
print("This is pass block",i)

print(i)

Answe >>> for i in [16,27,1281,494,74,75]:


r ... if(i>=128):
... pass
... print("This is pass block",i)
... print(i)
...
16
27
This is pass block 1281
1281
This is pass block 494
494
74
75

9. dogs = ["labrador"]
for i in dogs:
if i == "labrador":

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


dogs += ["pug"]
if i == "pug":
dogs += ["spitz"]
print(dogs)

Answe >>> dogs = ["labrador"]


r >>> for i in dogs:
... if i == "labrador":
... dogs += ["pug"]
... if i == "pug":
... dogs += ["spitz"]
... print(dogs)
...
['labrador', 'pug', 'spitz']

10. dogs = ["labrador"]


for i in dogs[:]:
if i == "labrador":
dogs += ["pug"]
if i == "pug":
dogs += ["spitz"]
print(dogs)

Answe >>> dogs = ["labrador"]


r >>> for i in dogs[:]:
... if i == "labrador":
... dogs += ["pug"]
... if i == "pug":
... dogs += ["spitz"]
... print(dogs)
...
['labrador', 'pug']

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


11. fibonacci = [0,1,1,2,3,5,8,13,21,26,83,90,101,108,120]
for i in range(len(fibonacci)):
print(i,fibonacci[i])

Answe >>> fibonacci = [0,1,1,2,3,5,8,13,21,26,83,90,101,108,120]


r >>> for i in range(len(fibonacci)):
... print(i,fibonacci[i])
...
00
11
21
32
43
55
68
7 13
8 21
9 26
10 83
11 90
12 101
13 108
14 120

12. numbers = [10, 40, 120, 230]


for i in numbers:
if i > 100:
break

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


print('current number', i)

Answe >>> numbers = [10, 40, 120, 230]


r >>> for i in numbers:
... if i > 100:
... break
... print('current number', i)
...
current number 10
current number 40

13. accounts=['Assets','Equity','Income','Expenses']
for account in accounts:
if account.startswith('I'):
print('Account name starts with I: '+account)
break
print('Account name does not start with I: '+account)

Answe >>> accounts=['Assets','Equity','Income','Expenses']


r >>> for account in accounts:
... if account.startswith('I'):
... print('Account name starts with I: '+account)
... break
... print('Account name does not start with I: '+account)
...
Account name does not start with I: Assets
Account name does not start with I: Equity
Account name starts with I: Income

14. for letter in 'Never Give Up':


if letter == 'U' or letter == 'G': # break the loop as soon it sees 'U' or

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


'G'
break
print('Current Letter :', letter)

Answe >>> for letter in 'Never Give Up':


r ... # break the loop as soon it sees 'U' or 'G'
... if letter == 'U' or letter == 'G':
... break
... print('Current Letter :',letter)
...
Current Letter : N
Current Letter : e
Current Letter : v
Current Letter : e
Current Letter : r
Current Letter :

15. Common_Name=["Saffron","Turmeric","Cumin","Nutmeg","Coriande
r","Cardamom"]
Botanical_Name=[["Crocus Sativus"],["Curcuma Longa"],["Cuminum
Cyminum"],["Myristica Fragrans"],
["Coriandrum Sativum"],["Elettaria Cardamomum"]]
m = len(Common_Name)
n = len(Botanical_Name)
for i in range(m):
n = len(Botanical_Name[i])
print(Common_Name[i])
for j in range(n):
print(Botanical_Name[i][j])

Answer >>>
Common_Name=["Saffron","Turmeric","Cumin","Nutmeg","Coriander","Car
damom"]
>>> Botanical_Name=[["Crocus Sativus"],["Curcuma Longa"],["Cuminum
Cyminum"],["Myristica Fragrans"],

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


... ["Coriandrum Sativum"],["Elettaria Cardamomum"]]
>>> m = len(Common_Name)
>>> n = len(Botanical_Name)
>>> for i in range(m):
... n = len(Botanical_Name[i])
... print(Common_Name[i])
... for j in range(n):
... print(Botanical_Name[i][j])
...
Saffron
Crocus Sativus
Turmeric
Curcuma Longa
Cumin
Cuminum Cyminum
Nutmeg
Myristica Fragrans
Coriander
Coriandrum Sativum
Cardamom
Elettaria Cardamomum
>>>

16. breakfast=["Appam","Idiappam","Idly","Dosai"]
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
for fooditems in breakfast:
if fooditems=="Idiappam":
print("Idiappam is healthy, as it has carbohydrates and fats!")
continue
print("You will be glad to consume,nutritious,delicious food like
"+fooditems)
else:
print("I want to see how the else block is working!")
print("Demonstrates that this part of the block will not be seen on the
screen")

Answe >>> breakfast=["Appam","Idiappam","Idly","Dosai"]


r >>> for fooditems in breakfast:
... if fooditems=="Idiappam":
... print("Idiappam is healthy, as it has carbohydrates and fats!")
... continue
... print("You will be glad to consume,nutritious,delicious food like
"+fooditems)
... else:
... print("I want to see how the else block is working!")
... print("Demonstrates that this part of the block will not be seen on the
screen")
...
You will be glad to consume,nutritious,delicious food like Appam
Idiappam is healthy, as it has carbohydrates and fats!
You will be glad to consume,nutritious,delicious food like Idly
You will be glad to consume,nutritious,delicious food like Dosai
I want to see how the else block is working!
Demonstrates that this part of the block will not be seen on the screen

17. healthy_fruits=[ "Amla", "Banana","Fig", "Guava",


"Jackfruit","Lemon", "Mango", "Orange","Papaya",
"Rambutan","Star Apple", "Watermelon"]
for item in healthy_fruits:
if item=='Is it ripe?':
print('yes it is ripe')
else:
pass
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
print('You can pick the fruit of your choice')

Answe >>> healthy_fruits=[ "Amla", "Banana","Fig", "Guava", "Jackfruit","Lemon",


r "Mango", "Orange","Papaya",
... "Rambutan","Star Apple", "Watermelon"]
>>> for item in healthy_fruits:
... if item=='Is it ripe?':
... print('yes it is ripe')
... else:
... pass
... print('You can pick the fruit of your choice')
...
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice
You can pick the fruit of your choice

18. Rewrite the following code after removing all syntax error(s). Also, list the
output
zoo_visitors =1008;
count = 0
i=1
while i <= zoo_visitors
count = count + i
i = i+1
Print("Total number of visitors to the zoo are ", count)

Answe zoo_visitors =1008;


r >>> count = 0
>>> i = 1
>>> while i <= zoo_visitors:
... count = count + i
... i = i+1
...
>>> print("Total number of visitors to the zoo are ", count)

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Total number of visitors to the zoo are 508536

19. Rewrite the following code after removing all syntax error(s). Also, list the
output
adjective=["green","small","yummy"]
fruits=["guava","mango","orange"]
for x in adj:
for y in fruits:
print(x,y)

Answe >>> adjective=["green","small","yummy"]


r >>> fruits=["guava","mango","orange"]
>>> for x in adjective:
... for y in fruits:
... print(x,y)
...
green guava
green mango
green orange
small guava
small mango
small orange
yummy guava
yummy mango
yummy orange

20. Remove any indentation mistakes from the following code and rewrite it.
Also provide a list of results.
for juice in ["Avacado","Celery","Cucumber","Lemon","Mango"]:
print(juice)
if juice[0]=="G":
break
print("Best Juice combo!")

Answe Case 1:
r
>>> for juice in ["Avacado","Celery","Cucumber","Lemon","Mango"]:
... print(juice)
... if juice[0]=="G":
File "<stdin>", line 3
if juice[0]=="G":
^^
SyntaxError: invalid syntax

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Case 2:

>>> for juice in ["Avacado","Celery","Cucumber","Lemon","Mango"]:


... print(juice)
... if juice[0]=="G":
... break
File "<stdin>", line 4
break
IndentationError: expected an indented block after 'if' statement on line 3

Case 3:

>>> for juice in ["Avacado","Celery","Cucumber","Lemon","Mango"]:


... print(juice)
... if juice[0]=="G":
... break
... print("Best Juice combo!")
File "<stdin>", line 5
print("Best Juice combo!")
^^^^^
SyntaxError: invalid syntax
>>>

Case 4:

The corrected code is :

>>> for juice in ["Avacado","Celery","Cucumber","Lemon","Mango"]:


... print(juice)
... if juice[0]=="G":
... break
... print("Best Juice combo!")
...
Avacado
Best Juice combo!
Celery
Best Juice combo!
Cucumber
Best Juice combo!
Lemon
Best Juice combo!
Mango
Best Juice combo!
>>>

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


21. Use a for loop with a continue statement to iterate over each of the
inputted numbers. When a nine-valued element is encountered, the
sequence advances to the next elements. Find and Write the output of the
following Python code:
x=[3,5,9,21,108,517,191,403,215,78,29,9]
for y in x:
if y == 9:
continue
print(y)

Answe >>> x=[3,5,9,21,108,517,191,403,215,78,29,9]


r >>> for y in x:
... if y == 9:
... continue
... print(y)
...
3
5
21
108
517
191
403
215
78
29

22. while True:


answer = input("")

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


if answer == '81':
print("The Greatness of a King!")
break
print("Courage, liberality, wisdom, energy, vigilance, knowledge,
bravery, unfailing virtue are the qualities of a leader")

Answe The above code has errors. The corrected code is given below with execution:
r

>>> while True:


... answer = input("")
... if answer == '81':
... print("The Greatness of a King!")
... break
...
... print("Courage, liberality, wisdom, energy, vigilance, knowledge,
bravery, unfailing virtue are the qualities of a leader")
...
12
Courage, liberality, wisdom, energy, vigilance, knowledge, bravery, unfailing
virtue are the qualities of a leader
81
The Greatness of a King!

(TryOut1.py)
while True:
answer = input("")
if answer == '81':
print("The Greatness of a King!")
break
print("Courage, liberality, wisdom, energy, vigilance, knowledge, bravery,
unfailing virtue are the qualities of a leader")

If input entered is a number other than 81,

If input entered is 81,then output is

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


23. for n in range(1278,5489,100):
pass
print(n)

Answe (TryOut2.py)
r
for n in range(1278,5489,100):
pass
print(n)

>>> for n in range(1278,5489,100):


... pass
...
>>> print(n)
5478

C:\Users\User> python >TryOut2.py


5478

24. a=108
while a<=254:
b=111
while b<=225:
print(b)
b+=100
a+=100
print("end of the inner loop")
print("end of the outer loop")

Answe (TryOut3.py)
r
a=108
while a<=254:
b=111
while b<=225:
print(b)
b+=100
a+=100
print("end of the inner loop")
print("end of the outer loop")

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


C:\Users\User> python >TryOut3.py
111
211
end of the inner loop
111
211
end of the inner loop
end of the outer loop

25. passengers=150
while passengers<155:
print("Ticket available")
passengers+=1
print("House full")

Answe (TryOut4.py)
r
passengers=150
while passengers<155:
print("Ticket available")
passengers+=1
print("House full")

C:\Users\User> python >TryOut3.py


Ticket available
Ticket available
Ticket available
Ticket available
Ticket available
House full

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
PROGRAMMING EXERCISES

1. Write a program to use a for loop and a continue statement to go through all of
the entered numbers one by one. The subsequent elements in the sequence are
activated when a particular element in the sequence has a value of 16.
Given x=[23,43,56,78,16,9,7,12,14,15]

Answe >>> x=[23,43,56,78,16,9,7,12,14,15]


r >>> for y in x:
... if y == 9:
... continue
... print(y)
...
23
43
56
78
16
7
12
14
15

2. Write python program that handles the following situation with while and if-
else statements.
“Gourmande patrons a restaurant on a regular basis. The Gourmande can
place an order from the restaurant's menu. If the order is identical to the

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


"Signature dish," the server notes it and takes it down; otherwise, they may
recommend the "Signature dish" instead of the favourite dish.”
(Exercise1.py)

Answe #Order the restaurant's "Signature_dish" to confirm its notoriety.


r print()
Signature_dish="Black Rice Pudding"
Gourmande=5
order_dinner=0
while order_dinner<Gourmande :
order_dinner+=1
your_fav_food =input("\nDear Gourmande!Which dish do you want to order?")

if your_fav_food==Signature_dish:
print("Your preferred food will be served in five
minutes.".format(Signature_dish))
else:
print("Dear Gourmande!Sorry!")
print( your_fav_food, "is not avaiable in the menu" )
print("Instead we can serve the restaurant's Signature_dish ",Signature_dish)

C:\Users\User> python >Exercise1.py

Dear Gourmande!Which dish do you want to order?Black Rice Pudding


Your preferred food will be served in five minutes.

Dear Gourmande!Which dish do you want to order?Jasmine Rice Pudding


Dear Gourmande!Sorry!
Jasmine Rice Pudding is not avaiable in the menu
Instead we can serve the restaurant's Signature_dish Black Rice Pudding

Dear Gourmande!Which dish do you want to order?

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


3. Make use of for loop statements in the code to deal with the following scenario.
“Books can be checked out as many times as needed, but the library only allows
10 visitors per day. Find out how many books were asked for in total.”
(Exercise2.py)

Answe print()
r students=6
totalbooks=0
for n in range(1,students+1):
books=int(input("\nHow many books do you need? "))
totalbooks=totalbooks+books
print("The number of books requested by {} student is {}".format(n,books))
print("Total sum of {} book requests from students equals
{}".format(n,totalbooks))

C:\Users\User> python >Exercise2.py

How many books do you need? 9


The number of books requested by 1 student is 9
Total sum of 1 book requests from students equals 9

How many books do you need? 2


The number of books requested by 2 student is 2
Total sum of 2 book requests from students equals 11

How many books do you need? 4

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


The number of books requested by 3 student is 4
Total sum of 3 book requests from students equals 15

How many books do you need? 6


The number of books requested by 4 student is 6
Total sum of 4 book requests from students equals 21

How many books do you need? 8


The number of books requested by 5 student is 8
Total sum of 5 book requests from students equals 29

How many books do you need? 5


The number of books requested by 6 student is 5
Total sum of 6 book requests from students equals 34

4. Make use of for-else loop, break statements in the code to deal with the
following scenario.
Due to pandemic regulations, an online store can only ship to a maximum of 6
USERS and upto 50 accessories at a time. Users 1 and 2 each place an order of
INR 78 and INR 54. As stock runs out, deny the third request.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


(Exercise3.py)
Answe print()
r users=6
accessories=11
for i in range(0,users):
booking_count=int(input("\nDear customer!!How many accessories you want to
be delivered: "))
if booking_count<=accessories:
print("Okay, we will deliver the products soon")
accessories=accessories-booking_count
else:
break

C:\Users\User> python >Exercise3.py

Dear customer!!How many accessories you want to be delivered: 2


Okay, we will deliver the products soon

Dear customer!!How many accessories you want to be delivered: 1


Okay, we will deliver the products soon

Dear customer!!How many accessories you want to be delivered: 3


Okay, we will deliver the products soon

Dear customer!!How many accessories you want to be delivered: 4


Okay, we will deliver the products soon

Dear customer!!How many accessories you want to be delivered: 5

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


5. Exhibit how Pass can be used as a placeholder for future code in a
(i).for loop in range(3,7).
(ii).for loop in range(12).
(Exercise4.py)

Answe (i).for loop in range(3,7).


r >>> for i in range(3,7):
... pass
...
>>> print(i)
11
(ii).for loop in range(12).
>>> for i in range(12):
... pass
...
>>> print(i)
11

print("pass as placeholder for range(3,7)")


for i in range(3,7):
pass # pass as placeholder
print(i)
print("pass as placeholder for range(12)")
for i in range(12):

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


pass # pass as placeholder
print(i)
C:\Users\ users\python>Exercise4.py
pass as placeholder for range(3,7)
6
pass as placeholder for range(12)
11

6. In this game, you have FIVE chances to win. The player will get what he wants
if his request is granted. If the programme continues, he can play again.

Write a for loop for this scenario, "In this game, you have FIVE chances to win.
The player will get what he wants if his request is granted. If the program
continues, he can play again."
(Exercise5.py)

Answe chances=5
r for i in range(0,chances):
decision=input("Do you wan to play the game again Y/N:")
if decision=="Y":
print("Game starts again")
if decision=="N":
print("Program terminated")
break

C:\Users\User> python >Exercise5.py


Do you wan to play the game again Y/N:Y
Game starts again
Do you wan to play the game again Y/N:Y
Game starts again
Do you wan to play the game again Y/N:N
Program terminated

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


7. Create a program to check whether the movie tickets are available or not?
(Exercise6.py)

Answe Available_tickets=10
r patrons=5
for i in range(0,patrons):
request=int(input("Dear Patron!! How many tickets you need?"))
if request <= Available_tickets:
print("Tickets are available")
Available_tickets=Available_tickets-request
else:
print("Tickets are not available they are sold")
break

C:\Users\User> python >Exercise6.py


Dear Patron!! How many tickets you need?7
Tickets are available
Dear Patron!! How many tickets you need?8
Tickets are not available they are sold

8 Iterate through the given string printing each letter using the for loop.
str="Hakuna Matata"

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Answe >>> str="Hakuna Matata"
r >>> for x in str:
... print (x)
...
H
a
k
u
n
a

M
a
t
a
t
a
>>>

9 Iterating through a fibonacci_series= (1,1,2,3,5,8,13,21,34,55,89) by using the


for loop as the primary control structure.

Answe >>> fibonacci_series= (1,1,2,3,5,8,13,21,34,55,89)


r
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
>>> for y in fibonacci_series:
... print (fibonacci_series)
...
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
>>>

10 Write p program to use multiple Python for loops in a nesting structure for the
fibonacci_series= (1,1,2,3,5,8,13,21,34,55,89)
(Exercise7.py)

Answe fibonacci_series= (1,1,2,3,5,8,13,21,34,55,89)


r total_sum=0
for x in fibonacci_series:
total_sum = total_sum+x
print(f'Total sum of numbers in fibonacci_series is {total_sum}')

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


C:\Users\User> python >Exercise7.py
Total sum of numbers in fibonacci_series is 232

11 Write a program using the for loop that outputs each word in the list.
rice= ["Arborio", "Wehani", "Basmati" ]
Also, print each word's characters instead?
(Exercise8.py)

Answe rice= ["Arborio", "Wehani", "Basmati" ]


r for y in rice:
print ("print the rice variety of "+y)
for x in y:
print (x)
print("")

C:\Users\User> python >Exercise8.py


print the rice variety of Arborio
A
r
b
o
r
i
o

print the rice variety of Wehani


W
e
h

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


a
n
i

print the rice variety of Basmati


B
a
s
m
a
t
i

12 Create a program utilising a for loop, an if statement and break in Python, to


post a list of rice and verify their presence or absence.
rice= ["Arborio", "Wehani", "Basmati" ]
(Exercise9.py)

Answe rice= ["Arborio", "Wehani", "Basmati" ]


r z =("Wehani")

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


x = False
for y in rice:
if z==y:
x = True
break
print(f'List contains {z}: {x}')

C:\Users\User> python >Exercise9.py


List contains Wehani: True

13 Convert the following loop into a for loop:


x=804
while(x<=1008):
print(x*100)
x+=15
(Exercise10.py)

Answe print('PROGRAM IN WHILE LOOP')


r x=804
while(x<=1008):
print(x*100)
x+=15
print('PROGRAM CONVERTED TO FOR LOOP')
for x in range(804,1009,15):
print(x*100)

C:\Users\User> python >Exercise10.py


PROGRAM IN WHILE LOOP
80400

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


81900
83400
84900
86400
87900
89400
90900
92400
93900
95400
96900
98400
99900
PROGRAM CONVERTED TO FOR LOOP
80400
81900
83400
84900
86400
87900
89400
90900
92400
93900
95400
96900
98400
99900

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


14 Create some code to generate the following pattern using two for loops.

Answe >>> for x in range(6,0,-1):


r ... for y in range(1,x+1):
... print(x,end=" ")
... print()
...
...
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


2 2
1
>>>

15 Create some code to generate the following pattern using two for loops.

Answe >>> for x in range(1,6):


r ... for y in range(1,x+1):
... print(x,end=" ")
... print()
...
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
>>>

16 Write a program using a while loop to calculate the mean(= total/25) of a set of
numbers using a while loop.
Given while loop condition = count<6
(Exercise11.py)
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
Answe count = 0
r total = 0.0
while(count<6):
x = float(input("User, type the number to calculate arithmetic mean: "))
count=count+1
total = total+x
mean = total/25;
print("Arithmetic mean is :", mean)

C:\Users\User> python >Exercise11.py


User, type the number to calculate arithmetic mean: 67
User, type the number to calculate arithmetic mean: 98
User, type the number to calculate arithmetic mean: 45
User, type the number to calculate arithmetic mean: 43
User, type the number to calculate arithmetic mean: 94
User, type the number to calculate arithmetic mean: 67
Arithmetic mean is : 16.56

17 Create a Python code that outputs all the multiples of 5, between 108 and 508.

Answe >>> for x in range(108,508):


r ... if (x%50==0):
... print(x)
...
150

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


200
250
300
350
400
450
500
>>>

18 Develop a Python code using for loop, which, in response to an integer input(x) from
the user, returns all the integers in line. Given range (18,25).
(Exercise12.py)

Answe x=int(input("Type the number "))


r for y in range(18,25):
print(x*y)

C:\Users\User> python >Exercise12.py


Type the number 98
1764
1862
1960
2058
2156
2254
2352

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


19 Create a programme to determine the highest common factor (HCF) or greatest
common divisor (GCD) of a pair of numbers.
(Exercise13.py)

Answe a = int(input('Dear User! Enter the first number ' ))


r b= int(input('Dear User! Enter the second number ' ))
c = min(a,b)
hcf= 0
for x in range(1,c+1):
if a%x== 0 and b%x == 0:
hcf =x
print(f"HCF of {a} and {b} is {hcf}.")

C:\Users\User> python >Exercise13.py


Dear User! Enter the first number 90
Dear User! Enter the second number 80
HCF of 90 and 80 is 10.

20 Write a Python Code to show all the odd numbers lying between any two input
numbers(1,9).
(Exercise14.py)

Answe x=int(input("Key in the first number:"))

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


r y=int(input("Key in the second number:"))
for z in range(x,y+1):
if(z%2!=0):
print(z)

C:\Users\User> python >Exercise14.py


Key in the first number:12
Key in the second number:15
13
15

21 Create a Python script that will flip any user-entered word.


(Exercise15.py)

Answe x = input("Key in the word to invert: ")


r for n in range(len(x) - 1, -1, -1):
print(x[n], end="")
print("\n")

C:\Users\User> python >Exercise15.py


Key in the word to invert: apple
elppa

22 Write a Python program that multiplies two integer numbers using repeated

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


addition (without using the ‘*’ operator)
(Exercise16.py)

Answe num1=int(input("Enter the First numbers :"))


r num2=int(input("Enter the Second number:"))
product=0
count=num1
while count >0:
count = count -1
product = product +num2
print("The multiplication of ",num1," and ",num2," is = ", product)

C:\Users\User> python >Exercise16.py


Enter the First numbers :240
Enter the Second number:568
The multiplication of 240 and 568 is = 136320

23 Write a Python Program to demonstrate the use of pass in a simple for- if loop .
Given range (2786,2799). Print when multiples of 5 are found.
(Exercise17.py)

Answe for num in range(786,799):


if num % 5 == 0:
r
print ("Found a multiple of 5: ")
pass
num+1
print ("Found number: ", num)

C:\Users\User> python >Exercise17.py


Found number: 786
Found number: 787

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Found number: 788
Found number: 789
Found a multiple of 5:
Found number: 790
Found number: 791
Found number: 792
Found number: 793
Found number: 794
Found a multiple of 5:
Found number: 795
Found number: 796
Found number: 797
Found number: 798

24 Create some code that uses an iterative for/else loop to cycle through the fruits
strings.
fruits=['Amla','Banana','Fig','Guava','Jackfruit','Lemon','Mango','Orange','P
apaya','Rambutan','Star Apple','Watermelon']
(Exercise18.py)

Answe fruits=['Amla','Banana','Fig','Guava','Jackfruit','Lemon','Mango','Orange','Papaya','Ra
r mbutan','Star Apple','Watermelon']

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


for item in fruits:
if item=='Jackfruit':
print('Look at the display screen for what is printed from IF block-Jackfruit')
else:
print(item)
print('This is from the else block')

C:\Users\User> python >Exercise18.py


Amla
This is from the else block
Banana
This is from the else block
Fig
This is from the else block
Guava
This is from the else block
Look at the display screen for what is printed from IF block-Jackfruit
Lemon
This is from the else block
Mango
This is from the else block
Orange
This is from the else block
Papaya
This is from the else block
Rambutan
This is from the else block
Star Apple
This is from the else block
Watermelon
This is from the else block

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


25 Create code that uses an iterative for/else loop to cycle through the fruits
strings. Show how a pass statement can be used in it.
Given sequence strings is
Juice=["Amla Juice","Orange Juice","Pomegranate Juice","Pineapple Juice"]
HealthiestJuice is the optional declared variable to be used in for loop
(Exercise19.py)

Answe Juice=["Amla Juice","Orange Juice","Pomegranate Juice","Pineapple Juice"]


r for HealthiestJuice in Juice:
if HealthiestJuice=="Orange Juice":
print('To showcase the execution of Pass,prints all the Juices ')
pass
print(HealthiestJuice)
print()

C:\Users\User> python >Exercise19.py


Amla Juice
To showcase the execution of Pass,prints all the Juices
Orange Juice

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Pomegranate Juice
Pineapple Juice

26 Create code that uses an iterative for/else loop to cycle through the fruits
strings. Show how a pass statement can be used in it.
Given sequence strings is
Juice=["Amla Juice","Orange Juice","Pomegranate Juice","Pineapple Juice"]
“HealthiestJuice” is the optional declared variable to be used in for loop
(Exercise20.py)

Answe Juice=["Amla Juice","Orange Juice","Pomegranate Juice","Pineapple Juice"]


r for HealthiestJuice in Juice:
if HealthiestJuice=="Orange Juice":
print('Upon encountering Orange Juice.skips it and prints other juices to
demonstrate continue.')
continue
print(HealthiestJuice)

C:\Users\User> python >Exercise20.py


Amla Juice
Upon encountering Orange Juice.skips it and prints other juices to demonstrate
continue.
Pomegranate Juice
Pineapple Juice

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


27 Write a Python programme to print the quadruple of positive numbers?
(Exercise21.py)

Answer while True:


x=int(input("Enter the positive number:"))
if x>0:
quadruple = x*x*x*x
print(quadruple)
else:
print("Program comes to an end")

C:\Users\User> python >Exercise21.py


Enter the positive number:2
16
Enter the positive number:5
625
Enter the positive number:-5
Program comes to an end
Enter the positive number:

28 Write a Python programme using break to print the triple of positive numbers?
(Exercise22.py)

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Answer while True:
x=int(input("Enter the positive number:"))
if x>0:
triple = x*x*x
print(triple)
else:
print("Program comes to an end")
break

C:\Users\User> python >Exercise22.py


Enter the positive number:12
1728

29 Construct a Python programme that returns a two-dimensional array with the


specified number of rows and columns, x and y respectively.

Construct a Python program that returns a 2D array with the specified number
of rows and columns, x and y respectively.
(Exercise23.py)

Answe x=int(input("Key in the required number of rows: "))


r y=int(input("Key in the required number of columns: "))
z = [[0 for y in range(y)] for row in range(x)]
for r in range(x):
for c in range(y):
z[r][c]= r*c
print(z)

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


C:\Users\User> python >Exercise23.py
Key in the required number of rows: 9
Key in the required number of columns: 4
[[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9], [0, 4, 8, 12], [0, 5, 10, 15], [0, 6, 12,
18], [0, 7, 14, 21], [0, 8, 16, 24]]

30 Create a script in Python that determines if a given number is a palindrome.


Given numbers:
[i] 7890987
[ii] 324576
Hint: Words, phrases, numbers, and
strings that read the same both ways are
palindromes.
(Exercise24.py)

Answe x=int(input("Key in the number:"))


r print('User, the number entered to determine the palindrome status is =' , x)
y=x
z=0
while(x>0):
w=x%10
z=z*10+w
x=x//10
if(y==z):
print('z=' , z)
print('y=' , y)
print("Yes the input number is a palindrome! when z= y ")
else:
print("No, the input number is not a palindrome!")

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


C:\Users\User> python >Exercise24.py
Key in the number:7890987
User, the number entered to determine the palindrome status is = 7890987
z= 7890987
y= 7890987
Yes the input number is a palindrome! when z= y

C:\Users\User> python >Exercise24.py


Key in the number:324576
User, the number entered to determine the palindrome status is = 324576
No, the input number is not a palindrome!

MCQ

Listed below are statements and questions. The statement or question will be followed
by four possible answers. Select the option that completes the statement or answers the
question.

1. What happens when the code that is shown below is put into action?

number = 7
while number <= 7:
if number < 7:

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


number = number + 3
print(number)

a. The while loop will never get executed


b. The value of number will be printed exactly 1 time
c. The program will loop indefinitely
d. The value of number will be printed exactly 5 times

Answer c. The program will loop indefinitely

2. Which of the following is the final output of the following code?


number = 0
while number <= 10:
print("Number: ", number)
number = number + 1

a. Number: 10
b. Number: number
c. Number: 0
d. Number: 11

Answer a. Number: 10

3. When the following line of code is executed, how many asterisks will be
printed?
for x in [0,1,2, 3]:
for y in [0, 1, 2, 3, 4]:
print('*')

a. 0
b. 4
c. 5
d. 20
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
Answer d.20

4. Infinite loop exists in the following code. Which of the following most
adequately explains why the loop does not end?
n = 10
answer = 1
while n > 0:
answer = answer + n
n=n+1
print(answer)

a. n starts at 10 and is incremented by 1 each time through the loop, so it will


always be positive.
b. answer starts at 1 and is incremented by n each time, so it will always be
positive.
c. You cannot compare n to 0 in the while loop. You must compare it to another
variable.
d. In the while loop body, we must set n to False, and this code does not do that.

Answer a. n starts at 10 and is incremented by 1 each time through the loop, so it


will always be positive.

5. What type of loop can be used to carry out the following iteration? Using
random selection, you pick a positive integer and output all the digits from
1 to the chosen value.

a. a for-loop or a while-loop
b. only a for-loop
c. only a while-loop
d. d. only for-while-loop

Answer a. a for-loop or a while-loop


COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
6. When run, what will the following Python code produce?
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)

a. [‘ab’, ‘cd’]
b. [‘AB’, ‘CD’]
c. [None, None]
d. [‘ABCD’, ‘ABCD’]

Answer a. [‘ab’, ‘cd’]

7. When run, what will the following Python code produce?


i=5
while True:
if i%0O11 == 0:
break
print(i)
i += 1

a. 5 6 7 8 9 10
b. 5678
c. 56
d. error

Answer b. 5 6 7 8

8. Regarding Python loops, which of the following is not true?

a. Loops are used to perform certain tasks repeatedly.


b. While loop is used when multiple statements are to executed repeatedly until
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
the given condition becomes False.
c. While loop is used when multiple statements are to executed repeatedly until
the given condition becomes True.
d. for loop can be used to iterate through the elements of lists.

Answer b. While loop is used when multiple statements are to executed repeatedly until
the given condition becomes False

9. For a given Python program, what results can we expect?


str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print(c)

a. 2
b. 0
c. 4
d. 3

Answer d. 3

10. Determine which of the following Python scripts will produce results that
are unique from the others.

a. for i in range(0,5):
print(i)
b. for j in [0,1,2,3,4]:
print(J)
c. for k in [0,1,2,3,4,5]:

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


print(k)
d. for l in range(0,5,1):
print(l)

Answer c. for k in [0,1,2,3,4,5]:


print(k)

11. What kind of iteration does Python's while loop perform?

a. indefinite
b. discriminant
c. definite
d. indeterminate

Answer a. indefinite

12. When the following code runs, what are the values of var1 and var2 that
are displayed?
output = ""
var1 = -2
var2 = 0
while var1 != 0:
var1 = var1 + 1
var2 = var2 - 1
print("var1: " + str(var1) + " var2 " + str(var2))

a. var1 = -2, var2 = 0


b. var1 = 0, var2 = -2
c. var1 = 0, var2 = -1
d. This is an infinite loop, so nothing will be printed

Answer b. var1 = 0, var2 = -2

13. Determine the outcome of the following code.


COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
for i in range(1,4):
for j in range(1,4):
print(i, j, end=' ')

a. 112233
b. 123123123
c. 111213212223313233
d. 112131212223313233

Answer c. 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3

14. Choose the correct statement(s) about the value of break.

a. Break stops the execution of entire program


b. Break halts the execution and forces the control out of the loop
c. Break forces the control out of the loop and starts the execution of next iteration
d. Break halts the execution of the loop for certain time frame

Answer b. Break halts the execution and forces the control out of the loop

15. Which part of code does the break statement cause to terminate execution?

a. Terminates a program
b. Only from innermost switch
c. From innermost loops or switches
d. Terminates a program

Answer a. Only from innermost loop

16. Which statement about for loop is true?

a. Index value is retained outside the loop


b. Index value can be changed from within the loop
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
c. Goto can be used to jump, out of the loop
d. All of these

Answer d. All of these

17. Choose the optimal statement between the "break" and "continue"
constructs.

a. "break" and "continue" can be used in "for", "while", "do-while" loop body and
"switch" body
b. "break" and "continue" can be used in "for", "while" and "do-while" loop body.
But only "break" can be used in "switch" body
c. "break" and "continue" can be used in "for", "while" and "do-while" loop body.
Besides, "continue" and "break" can be used in "switch" and "if-else" body
d. "break" can be used in "for", "while" and "do-while" loop body

Answer b. "break" and "continue" can be used in "for", "while" and "do-while" loop
body. But only "break" can be used in "switch" body

18. As long as the two loops' bodies don't make any references to each other,
they can be combined into a single loop using the ______ operator.

a. Loop unrolling
b. Strength reduction
c. Loop concatenation
d. Loop jamming

Answer d. Loop jamming

19. If the condition in a loop never reaches its _______ state, the loop is
infinite.

a. TRUE
COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD
b. FALSE
c. Null
d. Both A and C

Answer b.FALSE

20. To perform nothing, use the _______ statement.

a. Break
b. Exit
c. Return
d. Pass

Answer d.Pass

21. In what loops can you use a continue statement?

a. while loop
b. for loop
c. do-while
d. Both A and B

Answer d. Both A and B

22. Which of these arguments must be passed in a Python for loop?

a. Initial point.
b. Terminating Condition.
c. Hopping.
d. Index.

Answer b. Terminating Condition.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


23. What's the keyword for returning to the start of a loop when a certain
condition is met?

a. break
b. continue
c. raise
d. pass

Answer b.continue

24. The _ statement in Python is the combination of the break, continue, and
pass statements.

a. Jump
b. goto
c. compound
d. None of the mentioned above

Answer a.Jump

25. How does a while loop in Python differ from a for loop?

a. While loops can only count, for loops can loop anything.
b. A for loop can have multiple loop variables, but a while loop must have one.
c. When the number of iterations is known, use a for loop; otherwise, use a while
loop.
d. While and for loops are identical.

Answer c. When the number of iterations is known, use a for loop; otherwise, use a
while loop.

26. Which of the following keywords causes a while loop to end early?

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


a. continue
b. exit
c. break
d. return

Answer c.break

27. The iteration of a for loop can be skipped by using ----- keyword.

a. skip
b. continue
c. break
d. pass

Answer b. continue

28. What does the else block do in a Python for-else loop?

a. It executes when the loop is terminated by a break statement.


b. It executes when the loop has completed all iterations.
c. It executes when the loop encounters an exception.
d. There is no else block in a for-else loop.

Answer b.It executes when the loop has completed all iterations.

29. Explain why a for-else loop is preferable to a regular for loop in Python
code.

a. In comparison to a simple for loop, a for-else loop saves time and effort.
b. If the loop completes successfully, a for-else loop executes additional code.
c. For-else loops are easier to read and write than for loops.
d. A regular for loop is better than a for-else loop.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD


Answer b. If the loop completes successfully, a for-else loop executes additional code.

30. How does a while loop in Python differ from a while-else loop?

a. Both loops are identical.


b. If the condition is true, the code inside a while loop will continue to run
indefinitely; if the condition is false, the code inside an else block will be
executed.
c. While a while loop will run a specified number of times, a while-else loop can
run indefinitely.
d. A while loop will run regardless of whether the condition is true or false, but a
while-else loop will only run if the condition is true.

Answer b. If the condition is true, the code inside a while loop will continue to run
indefinitely; if the condition is false, the code inside an else block will
be executed.

COPYRIGHT © 2023 PEARSON INDIA EDUCATION SERVICES PVT. LTD

You might also like