Chapter 5
Chapter 5
CONCEPTUAL QUESTIONS
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.
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
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.
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?
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.
Answer The built-in function range () is a function that is used to repeat over a sequence of
numbers.
10. Give the syntax for the range function? Name the parameters inside the range
function?
Answer Syntax:
range(stop) or range(start, stop[, step])
12. Give the syntax for (a) while loop,(b) for loop,(c) jump statements.
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.
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]
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
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.
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
Answer
Answer
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.
26. Bring out the differences between the Pass and the Continue statements
TRY-OUT QUESTIONS
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")
2. chickens_hatched=0
while chickens_hatched< 6:
chickens_hatched+=1
if chickens_hatched== 9:
continue
print(chickens_hatched )
3. avocado=6
papya=9
while papya <12:
avocado=papya-1
papya=2*papya-avocado
print(papya,avocado)
4. for x in range(6,65,10):
print(x)
5. for x in range(2,10,2):
print(x*"Python")
7. i=0
while i<=8:
i+=1
if i == 5:
continue
print(i)
8. for i in [16,27,1281,494,74,75]:
if(i>=128):
pass
print("This is pass block",i)
print(i)
9. dogs = ["labrador"]
for i in dogs:
if i == "labrador":
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)
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"],
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")
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)
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)
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
Case 3:
Case 4:
Answe The above code has errors. The corrected code is given below with execution:
r
(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")
Answe (TryOut2.py)
r
for n in range(1278,5489,100):
pass
print(n)
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")
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")
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]
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
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)
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))
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.
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
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
8 Iterate through the given string printing each letter using the for loop.
str="Hakuna Matata"
M
a
t
a
t
a
>>>
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)
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)
15 Create some code to generate the following pattern using two for loops.
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)
17 Create a Python code that outputs all the multiples of 5, between 108 and 508.
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)
20 Write a Python Code to show all the odd numbers lying between any two input
numbers(1,9).
(Exercise14.py)
22 Write a Python program that multiplies two integer numbers using repeated
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)
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']
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)
28 Write a Python programme using break to print the triple of positive numbers?
(Exercise22.py)
Construct a Python program that returns a 2D array with the specified number
of rows and columns, x and y respectively.
(Exercise23.py)
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:
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)
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
a. [‘ab’, ‘cd’]
b. [‘AB’, ‘CD’]
c. [None, None]
d. [‘ABCD’, ‘ABCD’]
a. 5 6 7 8 9 10
b. 5678
c. 56
d. error
Answer b. 5 6 7 8
Answer b. While loop is used when multiple statements are to executed repeatedly until
the given condition becomes False
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]:
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. 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
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
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
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
a. Break
b. Exit
c. Return
d. Pass
Answer d.Pass
a. while loop
b. for loop
c. do-while
d. Both A and B
a. Initial point.
b. Terminating Condition.
c. Hopping.
d. Index.
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?
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
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.
30. How does a while loop in Python differ from a while-else loop?
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.