I am trying to make a program that detects how many vowels are in a word you type. Here's my source code (I have multiple codes):
a = input("word - ").lower()
for i in range(1, len(a)+1):
if a[str(i)] == "a" or "e" or "i" or "o" or "u":
print("ok")
else:
print("no")`
And I get the error:
TypeError: string indices must be integers
The second one:
a = input("word - ").lower()
for letter in a:
if letter == "a" or "e" or "i" or "o" or "u":
value = 0
value = value + 1
print(value)
Also gives me an error:
TypeError: string indices must be integers
The third one is a little bit more complex:
a = input("rec - ").lower()
for i in range(1, len(a)+1):
if a[str(i)] == "a":
print("yes a")
elif a[str(i)] == "e":
print("yes e")
elif a[str(i)] == "i":
print("yes i")
elif a[str(i)] == "o":
print("yes o")
elif a[str(i)] == "u":
print("yes u")
I am working on Python 3.6.1 on Repl.it
You can check out the full source code at my profile.
I appreciate your help. Thank you!
In the first and last example you used a string as an index (a[str(i)]). However, indeces are always integers. And remember that the first index is always 0, not 1. Your for-loop iterates from 1. Since the first element has an index of 0, the last has an index of len(array) - 1, meaning, that your for-loop should only iterate to len(a). The problem with the for-loop index also applies to the last example.
In the second example you didn't use the or-statements correctly. You can't compare them like that. You would have to write it like this:
if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":
To shorten this, just write:
if letter in "aeiou":
Here, you check whether the letter is in the string "aeiou".
In your second example you also reset value to zero everytime a vowel is found. This will lead to value being only either 1, or not defined. Put value = 0 before the for-loop and it should work.