Using for loops with strings - Answers
Q1. Enter this code and get it working:
myPhrase = input('Please enter a phrase with at least one word >>> ')
print('\n')
vowels='aeiou'
count = 0
for a in myPhrase:
print(a, end=' ')
if a in vowels:
count = count + 1
print('\n')
print('There are',count,'vowels in this phrase.')
input('Press <ENTER> to quit')
Q2. The code asks a user to enter a phrase and then attempts to count the number of vowels in the phrase.
Q3. The code won't count vowels that are in capitals. You can either change vowels='aeiou' to vowels='aeiouAEIOU' or use if a.lower() in vowels: to force the letter checked to be lower case.
Q4. To modify your program so that it counts and displays the number of words in the phrase:
myPhrase = input('Please enter a phrase, with at least one word >>> ')
print('\n')
vowels='aeiou'
count = 0
space = 0
for a in myPhrase:
print(a, end=' ')
if a.lower() in vowels:
count += 1
if a == ' ':
space += 1
print('\n')
print('There are',count,'vowels in this phrase.')
print('There are',space+1,'words in this phrase.')
input('Press <ENTER> to quit')
Q5. To modify your code so that it prints out each letter on its own line along with its ASCII code:
myPhrase = input('Please enter a phrase, with at least one word >>> ')
print('\n')
vowels='aeiou'
count = 0
space = 0
for a in myPhrase:
print(a, '\tASCII code:\t',ord(a))
if a.lower() in vowels:
count += 1
if a == ' ':
space += 1
print('\n')
print('There are',count,'vowels in this phrase.')
print('There are',space+1,'words in this phrase.')
input('Press <ENTER> to quit')