Python Exercise - Loops 1
Introduction
This unit covers Python loops, focusing on for
loops. You will practice using loops to solve various tasks that involve iterating through ranges and lists.
Task 1: Even and Odd Numbers
Description:
Practice using a loop to determine if numbers are even or odd.
Instructions:
- Write a
for
loop that iterates through the numbers from 1 to 20. - For each number, check if it is even or odd.
- Print the result for each number, indicating whether it is “even” or “odd”.
Task 2: Sum of Even Numbers
Description:
Use a loop to calculate the sum of all even numbers within a range.
Instructions:
- Write a
for
loop that iterates through the numbers from 1 to 100. - Use an
if
statement to check if the number is even. - Accumulate the sum of all even numbers and print the result at the end.
Task 3: D3TD5T
Description:
Combine loops and conditionals to categorize numbers.
Instructions:
- Write a
for
loop that iterates through the numbers from 1 to 30. - For numbers divisible by 3, print “D3T”.
- For numbers divisible by 5, print “D5T”.
- For numbers divisible by both 3 and 5, print “D3TD5T”.
- For all other numbers, just print the number.
Task 4: Find a Friend
Description:
Use a loop to search for an item in a list.
Instructions:
- Define a list of friends’ names, such as
["Anna", "Ben", "Clara", "David", "Eva"]
. - Use a
for
loop to search for a specific friend (e.g., “Clara”). - If the friend is found, print a message that they were found.
Task 5: Replace a Character in a List of Fruits
Description:
Use a loop to replace characters in strings.
Instructions:
- Define a list of fruit names, such as
["apple", "banana", "cherry"]
. - Use a
for
loop to go through each fruit. - Replace occurrences of a specific character (e.g., replace “a” with “o”) in each word.
- Print the modified list.
Task 6: Modify a List of Friends
Description:
Practice modifying elements of a list using loops.
Instructions:
- Define a list of friends
["Anna", "Ben", "Clara", "David", "Eva"]
. - Use a
for
loop to remove “Ben” and replace “Anna” with “Bella”. - Add a new friend, “Felix”, at position 1 in the list.
- Print the modified list.