What's wrong with this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What's wrong with this code?

I tried to create a program to count vowels on Python. My Idea was to create a list of vowels, then I'd convert the user input into a list and use a function to count the vowels like this: vowels = ["a", "e", "i", "o", "u"] det count_vowels(x): i = 0 for letter in x and vowels: i += 1 print(i) while True: word = input("Enter a word: ") letters = list(word) count_vowels(letters) The program just outputs 1 2 3 4 5 for every word I input. What's wrong?

18th Jan 2018, 9:34 PM
Antônio Gabriel Zeni Landim
Antônio Gabriel Zeni Landim - avatar
6 Answers
+ 1
vowels = ["a","e","i","o","u"] def count_vowels(x) i = 0 for l in x: if l in vowels: i += 1 elif x[-1] == l return i while True: word = input ("Enter a word: ") letters = list(word) count_vowels(letters) print(count_vowels(letters)) That elif statement should help. It’s checking if x[-1] which equals the last letter of the string and seeing if it is equal to whatever is in l. Only on the last iteration will the statement execute, returning the value of i which is the number of vowels in the string
19th Jan 2018, 4:21 AM
Travis
Travis - avatar
+ 1
I think the problem is that the function is only counting the elements of the vowels list, so there's something to do with the use of the boolean operator 'and' but Idk how to solve it.
18th Jan 2018, 9:36 PM
Antônio Gabriel Zeni Landim
Antônio Gabriel Zeni Landim - avatar
+ 1
Try doing: for letter in x: if letter in vowels: i += 1 Also, it’s printing that because you’re printing i after every iteration in the for loop You’ll want to do return i after iterating all the way through x
18th Jan 2018, 11:18 PM
Travis
Travis - avatar
+ 1
Thank you very much, Travis. Coding is addictive even to people who can't do much more than couting vowels.
18th Jan 2018, 11:23 PM
Antônio Gabriel Zeni Landim
Antônio Gabriel Zeni Landim - avatar
+ 1
Well, the output now is only 1 :/ Doing it as: vowels = ["a","e","i","o","u"] def count_vowels(x) i = 0 for l in x: if l in vowels: i += 1 return i while True: word = input ("Enter a word: ") letters = list(word) count_vowels(letters) print(count_vowels(letters))
19th Jan 2018, 12:45 AM
Antônio Gabriel Zeni Landim
Antônio Gabriel Zeni Landim - avatar
0
No problem man, everyone starts somewhere and I’m pretty new myself to python.
18th Jan 2018, 11:33 PM
Travis
Travis - avatar