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:

  1. Write a for loop that iterates through the numbers from 1 to 20.
  2. For each number, check if it is even or odd.
  3. 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:

  1. Write a for loop that iterates through the numbers from 1 to 100.
  2. Use an if statement to check if the number is even.
  3. 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:

  1. Write a for loop that iterates through the numbers from 1 to 30.
  2. For numbers divisible by 3, print “D3T”.
  3. For numbers divisible by 5, print “D5T”.
  4. For numbers divisible by both 3 and 5, print “D3TD5T”.
  5. 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:

  1. Define a list of friends’ names, such as ["Anna", "Ben", "Clara", "David", "Eva"].
  2. Use a for loop to search for a specific friend (e.g., “Clara”).
  3. 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:

  1. Define a list of fruit names, such as ["apple", "banana", "cherry"].
  2. Use a for loop to go through each fruit.
  3. Replace occurrences of a specific character (e.g., replace “a” with “o”) in each word.
  4. Print the modified list.

Task 6: Modify a List of Friends

Description:

Practice modifying elements of a list using loops.

Instructions:

  1. Define a list of friends ["Anna", "Ben", "Clara", "David", "Eva"].
  2. Use a for loop to remove “Ben” and replace “Anna” with “Bella”.
  3. Add a new friend, “Felix”, at position 1 in the list.
  4. Print the modified list.

Updated: