Touchpad Computer Book Class 8 Ch 8 solution

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.

Touchpad Computer Book Class 8 Ch 8 solution


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:

Python
for variable in sequence:
# Code to execute on each iteration

Example:

Python
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:

    python
     
    for i in range(5):
    if i == 3:
    break
    print(i)

    Output:

     
    0
    1
    2

    In this example, the loop stops when i equals 3 due to the break statement.

  • continue Statement: Skips the current iteration and moves to the next one.

    Example:

    Python
     
    for i in range(5):
    if i == 2:
    continue
    print(i)

    Output:

     
    0
    1
    3
    4

    Here, the loop skips printing 2 because of the continue 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:

Python
while condition:
# Code to execute

Example:

Python
count = 1
while count <= 5:
print("Count is:", count)
count += 1

Output:

csharp
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 Loop

    Python
     
    total = 0
    for num in range(1, 11):
    total += num
    print("Sum:", total)

    Output:

    makefile
     
    Sum: 55
  • Example 2: Find if a Number is Prime Using a while Loop

    Python
     
    num = 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 and continue

    Python
     
    for 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

  1. 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

  1. 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, false

    • c. The infinite loop never ends.
      Answer: infinite

    • d. The break and continue are the jump statements in Python.
      Answer: break, continue


  1. Write “T” for true and “F” for false.

    • a. We can use a do-while loop in Python.
      Answer: F

    • b. The continue statement breaks the loops one by one.
      Answer: F

    • c. To come out of the infinite loop, we can either close the program window or press Ctrl + C.
      Answer: T

    • d. A sequence is a succession of values bound together by a single name.
      Answer: T

    • e. The while statement is the looping statement.
      Answer: T


  1. 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 the for loop in Python is:

    Python
     
    for variable in range(start, stop, step):
    # Code to execute

    c. What is the use of Jump statement?
    Answer: Jump statements, like break and continue, control the flow of loops by either ending the loop prematurely (break) or skipping to the next iteration (continue).


  1. 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: The while statement repeatedly executes a block of code as long as a given condition is true. For example:

    Python
     
    i = 1
    while i < 5:
    print(i)
    i += 1

    Flowchart: Start -> Condition -> Execute -> Update -> Repeat or End.

    c. Distinguish between continue and break statements.
    Answer: The break statement terminates the loop entirely, while the continue statement skips the current iteration and proceeds with the next iteration of the loop.

Let’s Solve: Write the output of the following programs

  1. Program 1:

    Python
     
    x = 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
  2. Program 2:

    Python
     
    fruits = ["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
  3. Program 3:

    Python
     
    i = 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 if i is divisible by 3. If not, it prints i and increments it by 2. The loop stops when i becomes divisible by 3.
    • Output:
      2
      4
  4. Program 4:

    Python
     
    i = 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. When i reaches 3, the break statement ends the loop, so the else the part does not execute.
    • Output:
      0
      0
      1
      0
      2
  5. Program 5:

    Python
     
    i = 0
    while i < 3:
    print(i)
    i += 1
    else:
    print(0)
    • Explanation: This program prints i until i is less than 3. After exiting the loop, the else statement executes, printing 0.
    • Output:
       
      0
      1
      2
      0

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

  1. Determine whether a given number is an Armstrong number or not.

    Python
     

    num = int(input("Enter a number: "))
    sum = 0
    temp = num
    order = len(str(num)) # Number of digits in the number

    while temp > 0:
    digit = temp % 10
    sum += digit ** order
    temp //= 10

    if 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.

  2. Python
     
    for i in range(8, 90, 3): # Starting at 8, incrementing by 3 until 89
    print(i, end=" ")
  3. Use the for loop to print the numbers 108, 98, 96, …, 4, 2.

    Python
     
    for i in range(108, 0, -2): # Starting at 108, decrementing by 2 until 2
    print(i, end=" ")
  4. Print 1 to 100 using a while loop.

    Python
     
    i = 1
    while i <= 100:
    print(i, end=" ")
    i += 1
  5. Find out the sum of numbers within the range 1 to 100 using a while loop.

    Python
     
    i = 1
    sum = 0
    while i <= 100:
    sum += i
    i += 1
    print("Sum of numbers from 1 to 100:", sum)
  6. Calculate the sum of first ten even numbers by using the while loop and the for loop.

    • Using a while loop:

      Python
       
      i = 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:

      Python
       
      sum = 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)
  7. Print first 20 odd numbers in decreasing order using a while loop.

    Python
     
    i = 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.

Scroll to Top