- Read the question carefully (twice).
- Break the task into the smallest steps.
- Sketch or write pseudocode before coding.
- Start small — test as you go.
- Check your solution with different cases.
You will learn how to work with strings in Python, including how to find the length of a string, use indexing, and extract characters. You will also practice thinking about odd and even numbers.
Background
A string is a sequence of characters, like "hello" or "computer". Each character in a string has a position called an index.
- Python starts counting at 0, so in
"hello":"h"is at index 0"e"is at index 1"l"is at index 2"l"is at index 3"o"is at index 4
The function len(string) tells us how many characters are in the string.
The middle character(s) are found like this:
- If the string length is odd → return one middle character.
- Example:
"cat"→ middle letter is"a".
- Example:
- If the string length is even → return the two middle characters.
- Example:
"test"→ middle letters are"es".
- Example:
Tasks
Task 1: Trace It
Trace what the following code will print:
word = "python"
length = len(word)
middle = length // 2
print(word[middle-1:middle+1])
Question: What will the output be? Show your working.
Task 2: Write a Function
Write a function middle_letter(word) that:
- Finds the length of the string.
- If the length is odd, returns the single middle character.
- If the length is even, returns the two middle characters.
Example:
print(middle_letter("cat")) # Output: a
print(middle_letter("dogs")) # Output: og
Task 3: Test Your Function
Test your function with at least five different strings, including:
- A one-letter word (e.g.
"a") - A three-letter word (e.g.
"sun") - A four-letter word (e.g.
"code") - A longer odd-length word (e.g.
"banana") - A longer even-length word (e.g.
"school")
Write down the output of your program for each test case.
Task 4: Explain
Question:
Why do we need to treat odd-length and even-length strings differently when finding the middle letter(s)?
Success Criteria
By the end of this task you should be able to:
- Correctly find the length of a string using
len(). - Use indexing and slicing to extract specific characters from a string.
- Write a Python function that works with both odd and even length strings.
- Explain why odd and even lengths produce different results for the middle.