CLASS LOOP IMPORTANT EXAMPLES : DO PRACTICE IN COMPUTER LAB

Sure! Here's a worksheet focusing on using the for loop in programming, but without involving nested loops. This will help you get comfortable with basic iteration techniques. I’ll provide some problems along with sample solutions to illustrate the concepts.




For Loop Worksheet

Problem 1: Basic Iteration

Task: Write a for loop that prints the numbers from 1 to 10.

Example Output:

1
2
3
4
5
6
7
8
9
10

Solution:


for i in range(1, 11):
print(i)

Problem 2: Summing Numbers

Task: Write a for loop to calculate the sum of the numbers from 1 to 100.

Example Output:

Solution:

python
total = 0
for i in range(1, 101):
total += i # total=total+i
print(total)

Problem 3: List Iteration

Task: Given a list of numbers, write a for loop to print each number doubled. (just do practice , about list you will learn in upcoming classes )

Example Input:

python
numbers = [2, 4, 6, 8, 10]

Example Output:


4
8
12
16
20

Solution:


numbers = [2, 4, 6, 8, 10]
for number in numbers:
print(number * 2)

Problem 4: Counting Elements

Task: Write a for loop to count the number of occurrences of the letter 'a' in a given string.

Example Input:

text = "apples are amazing"

Example Output:


3

Solution:

text = "apples are amazing"
count = 0
for char in text:
if char == 'a':
count += 1
print(count)

Problem 5: Create a Multiplication Table

Task: Write a for loop to generate a multiplication table for the number 5 up to 10.

Example Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Solution:

python

number = 5
for i in range(1, 11):
print(number,"X",i,"=",number*i)

Problem 6: Filter Even Numbers

Task: Write a for loop that filters out and prints only the even numbers from a list.

Example Input:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example Output:

2
4
6
8
10

Solution:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number % 2 == 0:
print(number)

Problem 7: Reverse a String

Task: Write a for loop to reverse a given string.

Example Input:

text = "hello"

Example Output:


olleh

Solution:

text = "hello"
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(reversed_text)

Post a Comment

0 Comments