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
2345678910
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:
pythontotal = 0for 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:
pythonnumbers = [2, 4, 6, 8, 10]
Example Output:
4
8121620
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 = 0for char in text: if char == 'a': count += 1print(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 = 105 x 3 = 155 x 4 = 205 x 5 = 255 x 6 = 305 x 7 = 355 x 8 = 405 x 9 = 455 x 10 = 50
Solution:
python
number = 5for 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
46810
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_textprint(reversed_text)
0 Comments
Please do note create link post in comment section