script_12.py - Count Vowels in a String
Code
#!/usr/bin/env python3
"""Count vowels in a string"""
text = input("Enter text: ")
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"Number of vowels: {count}")
Explanation
Line 4: text = input("Enter text: ")
- text is string type, stores input to analyze
Line 5: vowels = "aeiouAEIOU"
- String literal containing all vowels (lowercase and uppercase)
- Used as a set of characters to check against
- String type, but treated like a collection
Line 6: count = 0
- Counter variable initialized to 0 (integer type)
- Will be incremented in loop
Line 8: for char in text:
- Iterates over each character in string
- char is string of length 1 (single character)
Line 9: if char in vowels:
- in checks if char exists anywhere in vowels string
- Returns boolean
- Works because strings are sequences of characters
Line 10: count += 1
- Increments counter by 1
- Only executes when character is a vowel
- += equivalent to count = count + 1