Touchpad Computer Book Class 8 Ch 8 solution
Loops in Python
Loops are fundamental in Python programming, allowing you to execute a block of code multiple times. They’re particularly useful for tasks involving repetitive actions or iterating over data structures like lists and dictionaries. This chapter dives into Python’s main loop types — the for
loop and the while
loop — and introduces jump statements like break
and continue
, which give you control over loop behavior.
1. The for
Loop in Python
The for
loop is commonly used to iterate over a sequence (like a list, tuple, string, or range). It executes a block of code once for each item in the sequence.
Syntax:
for variable in sequence:
# Code to execute on each iteration
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
In this example, the for
the loop iterates through each item in the list fruits
, printing each one.
2. Jump Statements in Python
Jump statements, such as break
and continue
, are used to control the flow of loops. They allow you to alter the loop’s behavior based on certain conditions.
break
Statement: Terminates the loop entirely when encountered.Example:
pythonfor i in range(5):
if i == 3:
break
print(i)Output:
0
1
2In this example, the loop stops when
i
equals 3 due to thebreak
statement.continue
Statement: Skips the current iteration and moves to the next one.Example:
Pythonfor i in range(5):
if i == 2:
continue
print(i)Output:
0
1
3
4Here, the loop skips printing
2
because of thecontinue
statement.
3. The while
Loop in Python
The while
loop repeatedly executes a block of code as long as a given condition is true. This loop is especially useful when the number of iterations isn’t known beforehand.
Syntax:
while condition:
# Code to execute
Example:
count = 1
while count <= 5:
print("Count is:", count)
count += 1
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
This example shows a while
loop that continues to run until count
is greater than 5.
4. Practical Examples of Loops in Python
Here are a few more examples to help you practice and understand loops in Python:
Example 1: Sum of Numbers from 1 to 10 Using a
for
LoopPythontotal = 0
for num in range(1, 11):
total += num
print("Sum:", total)Output:
makefileSum: 55
Example 2: Find if a Number is Prime Using a
while
LoopPythonnum = int(input("Enter a number: "))
is_prime = True
i = 2
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime and num > 1:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")Example 3: Print the First 10 Even Numbers Using a
for
Loop andcontinue
Pythonfor i in range(1, 21):
if i % 2 != 0:
continue
print(i)Output:
2
4
6
8
10
12
14
16
18
20
Touchpad Computer Book Class 8 Ch 8 solution
Test Your Skills
Tick (✓) the correct option.
a. What does a
do while
loop do?- (i) Repeat a chunk of code a given number of times
- (ii) Repeat a chunk of code until a condition is true
- (iii) Repeat a chunk of code until a condition is false
- (iv) Repeat a chunk of code indefinitely
Answer: (ii) Repeat a chunk of code until a condition is true
b. Which of the following is a looping statement in Python?
- (i)
for
statement - (ii)
while
statement - (iii)
if
statement - (iv)
break
statement
Answer: (i)for
statement
c. Which of the following statements allows repeating a task for a fixed number of times?
- (i)
for
statement - (ii)
while
statement - (iii)
if...else
statement - (iv)
continue
statement
Answer: (i)for
statement
d. Which of the following statements terminates the execution of the loop?
- (i)
if
- (ii)
for
- (iii)
break
- (iv)
continue
Answer: (iii)break
Fill in the blanks using the words from the help box.
Help Box: infinite, break, while, continue, non-zero
a. The
while
statement executes a set of statements repeatedly until the logical expression remains true.
Answer:while
b. Any non-zero value in the
while
loop indicates an always-true condition, whereas zero indicates a false condition.
Answer: non-zero, falsec. The infinite loop never ends.
Answer: infinited. The break and continue are the jump statements in Python.
Answer: break, continue
Write “T” for true and “F” for false.
a. We can use a do-while loop in Python.
Answer: Fb. The continue statement breaks the loops one by one.
Answer: Fc. To come out of the infinite loop, we can either close the program window or press Ctrl + C.
Answer: Td. A sequence is a succession of values bound together by a single name.
Answer: Te. The
while
statement is the looping statement.
Answer: T
Short answer type questions.
a. What is looping?
Answer: Looping is a programming concept that repeats a block of code as long as a specified condition is true.b. Write the syntax for the
for
loop.
Answer: The syntax of thefor
loop in Python is:Pythonfor variable in range(start, stop, step):
# Code to executec. What is the use of Jump statement?
Answer: Jump statements, likebreak
andcontinue
, control the flow of loops by either ending the loop prematurely (break
) or skipping to the next iteration (continue
).
Long answer type questions.
a. Draw the flowchart of the
for
loop.
Answer: The flowchart involves these steps: Start -> Initialize -> Condition Check -> Execute -> Increment/Decrement -> Loop or End.b. Define the use of
while
statement with the help of an example and flowchart.
Answer: Thewhile
statement repeatedly executes a block of code as long as a given condition is true. For example:Pythoni = 1
while i < 5:
print(i)
i += 1Flowchart: Start -> Condition -> Execute -> Update -> Repeat or End.
c. Distinguish between
continue
andbreak
statements.
Answer: Thebreak
statement terminates the loop entirely, while thecontinue
statement skips the current iteration and proceeds with the next iteration of the loop.
Let’s Solve: Write the output of the following programs
Program 1:
Pythonx = 1
sum = 0
while (x <= 10):
sum = sum + x
x = x + 1
print(sum)- Explanation: This program calculates the sum of numbers from 1 to 10.
- Output:
55
Program 2:
Pythonfruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)- Explanation: This program iterates over a list of fruits and prints each fruit.
- Output:
apple
banana
cherry
Program 3:
Pythoni = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2- Explanation: This program starts with
i = 2
, and on each iteration, it checks ifi
is divisible by 3. If not, it printsi
and increments it by 2. The loop stops wheni
becomes divisible by 3. - Output:
2
4
- Explanation: This program starts with
Program 4:
Pythoni = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)- Explanation: This program prints
i
while incrementing it by 1 on each iteration. Wheni
reaches 3, thebreak
statement ends the loop, so theelse
the part does not execute. - Output:
0
0
1
0
2
- Explanation: This program prints
Program 5:
Pythoni = 0
while i < 3:
print(i)
i += 1
else:
print(0)- Explanation: This program prints
i
untili
is less than 3. After exiting the loop, theelse
statement executes, printing0
. - Output:
0
1
2
0
- Explanation: This program prints
These are the outputs of each code snippet in the Let’s Solve section based on Python execution. Let me know if you need further explanations or any additional assistance!
Tech Practice: Write a program to
Determine whether a given number is an Armstrong number or not.
Pythonnum = int(input("Enter a number: "))
sum = 0
temp = num
order = len(str(num)) # Number of digits in the numberwhile temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10if num == sum:
print(num, “is an Armstrong number”)
else:
print(num, “is not an Armstrong number”)Use the for loop to print the numbers 8, 11, 14, 17, 20, …, 83, 86, 89.
- Python
for i in range(8, 90, 3): # Starting at 8, incrementing by 3 until 89
print(i, end=" ") Use the for loop to print the numbers 108, 98, 96, …, 4, 2.
Pythonfor i in range(108, 0, -2): # Starting at 108, decrementing by 2 until 2
print(i, end=" ")Print 1 to 100 using a while loop.
Pythoni = 1
while i <= 100:
print(i, end=" ")
i += 1Find out the sum of numbers within the range 1 to 100 using a while loop.
Pythoni = 1
sum = 0
while i <= 100:
sum += i
i += 1
print("Sum of numbers from 1 to 100:", sum)Calculate the sum of first ten even numbers by using the while loop and the for loop.
Using a while loop:
Pythoni = 2
sum = 0
count = 0
while count < 10:
sum += i
i += 2
count += 1
print("Sum of first ten even numbers (while loop):", sum)Using a for loop:
Pythonsum = 0
for i in range(2, 21, 2): # First ten even numbers (2 to 20)
sum += i
print("Sum of first ten even numbers (for loop):", sum)
Print first 20 odd numbers in decreasing order using a while loop.
Pythoni = 39 # Start from 39 (20th odd number)
count = 0
while count < 20:
print(i, end=" ")
i -= 2
count += 1
Touchpad Computer Book Class 8 Ch 8 solution
This solution is useful for the students of the CBSE and HBSE boards.
Visit vacancyconnect.com regularly for more valuable & Real Information.
Conclusion
Loops and jump statements are essential tools in Python, making it easy to perform repetitive tasks and manage control flow within loops. By understanding how to use the for
and while
loops, along with the break
and continue
statements, you’ll be well-equipped to write efficient and effective Python programs.
This post provides a strong foundation in Python’s loop structures and jump statements, making it ideal for beginners and anyone looking to improve their Python skills.