Back to Module 3

Exercises

These exercises are written for beginners. Do them in order.

Exercise 1. Practice with strings

Assign "programming" to a variable named s.

Then print:

  • the first character
  • the last character
  • the substring "gram"

Starter code:

s = "programming"

print(s[0])
print(s[-1])
print(s[3:7])

Exercise 2. Practice with lists

Create this list:

fruits = ["apple", "banana", "cherry"]

Now do these steps one by one:

  1. Append "date"
  2. Replace "banana" with "blueberry"
  3. Print everything except the first item

Starter code:

fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[1] = "blueberry"
print(fruits[1:])

Exercise 3. Practice with conditionals

Given n = 7, write an if statement that prints whether the number is even or odd.

Hint:

  • Use the remainder operator %

Starter code:

n = 7

if n % 2 == 0:
    print("even")
else:
    print("odd")

Exercise 4. Practice with loops

Write a for loop over the list below and print each number divided by 2.

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

Starter code:

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

for n in numbers:
    print(n / 2)

Exercise 5. Combine loops and functions

Write a function named filter_long_words(words, min_length).

The function should:

  • take a list of words
  • keep only the words whose length is greater than or equal to min_length
  • return the new list

Test data:

words = ["data", "analysis", "python", "AI"]

Starter code:

def filter_long_words(words, min_length):
    result = []
    for word in words:
        if len(word) >= min_length:
            result.append(word)
    return result

words = ["data", "analysis", "python", "AI"]
print(filter_long_words(words, 5))

Expected result:

['analysis', 'python']

Extra challenge

Change the test data and try the function again with:

  • min_length = 4
  • min_length = 6

Back to Module 3