String Assignment Explanation
1. What is a string?
A string is a sequence of characters enclosed in quotes (single, double, or triple quotes).
Example:
text = "Hello, World!"
Strings can contain letters, numbers, and symbols, and can be looped through, modified, or
checked for specific letters.
2. Assignment:
Write a function count_vowels(text) that counts and returns the number of vowels in a given
sentence.
3. Solution (Python Code):
def count_vowels(text):
vowels = "aeiouAEIOU" # All vowels (lowercase and uppercase)
count = 0 # Initialize counter
for char in text: # Loop through each character in the string
if char in vowels: # Check if the character is a vowel
count += 1 # Increase the count
return count # Return total number of vowels
sentence = input("Enter a sentence: ")
print("Number of vowels:", count_vowels(sentence))
4. Step-by-Step Explanation:
- Define a string of vowels containing all vowel letters.
- Loop through each character in the sentence.
- If the character is a vowel, increase the count.
- Finally, return the total number of vowels found.
5. Example Run:
Input: Programming is fun
Output: Number of vowels: 5
(Explanation: The vowels are o, a, i, i, u — total = 5)