Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Double letters

The goal of this challenge is to analyze a string to check if it contains two of the same letter in a row. For example, the string "hello" has l twice in a row, while the string "nono" does not have two identical letters in a row.

Define a function named double_letters that takes a single parameter. The parameter is a string. Your function must return True if there are two identical letters in a row in the string, and False otherwise.

 

==== SOLUTION ====

You can implement the `double_letters` function in Python by iterating through the characters of the string and checking if any two adjacent characters are the same. Here’s how you can do it:

“`python
def double_letters(s):
      for i in range(len(s) – 1):
          if s[i] == s[i + 1]:
               return True
      return False

# Test the function
print(double_letters(“hello”)) # Output: True
print(double_letters(“nono”)) # Output: False
“`

Explanation:

1. `def double_letters(s):`: This line defines a function named `double_letters` that takes a single parameter `s`, which is a string.

2. `for i in range(len(s) – 1):`: This line sets up a loop that iterates through the indices of the string `s`, except for the last index, because we need to compare each character with the one next to it.

3. `if s[i] == s[i + 1]:`: Inside the loop, this line checks if the character at index `i` is the same as the character at index `i + 1`, i.e., if two adjacent characters are the same.

4. `return True`: If two identical letters in a row are found, the function immediately returns `True`.

5. `return False`: If the loop completes without finding two identical letters in a row, the function returns `False`.

So, when you call `double_letters(“hello”)`, it returns `True` because there are two identical letters ‘l’ in a row. Similarly, when you call `double_letters(“nono”)`, it returns `False` because there are no two identical letters in a row.

Join the conversation