A problem with a loop

Suppose you wanted to find out if a string contained a vowel, and if so, where the FIRST one was, from the left. Yes, there may be a Python function for this, but what if you had to write it yourself? Assume str has some value, like "cat".

First attempt:

i = 0
first = -1
while i < len(str):
	if str[i] == "a" 
		or str[i] == "e" or str[i] == "i"
		or str[i] == "o" or str[i] == "u"
		or str[i] == "A" or str[i] == "E"
		or str[i] == "I" or str[i] == "O"
		or str[i] == "U":
			first = i
	i += 1

if first == -1:
    print ("no vowels in word")
else:
    print("Vowel found at", first)

First question - can we shorten it? yes - put str[i] into a variable, and force it to upper case

i = 0
first = -1
while i < len(str):
	ch = str[i].upper()
	if ch == "A" or ch == "E" or ch == "I" or ch == "O" or ch == "U":
   	   first = i
	i += 1

if first == -1:
    print("no vowels in word ")
else:
    print("Vowel found at", first)

Actually this code is not right! It will actually find the LAST one in the string, not the FIRST one. You want to get out of the loop as SOON as the code finds ANY of the vowels.

First impulse - force i to be the ending value to force an exit from the loop.

	if ch == "A" or ch == "E" or ch == "I" or ch == "O" or ch == "U":
		first = i
		i = len(str)## new code here
		

This does work BUT it is not good style. Right now the top of the loop implies that it is a counter controlled loop, that i is starting at 0 and goes through every single character of the string, to the end. But this is not the case in reality, it could stop as soon as the very first character!

It is better to make the loop condition document ALL of the conditions under which the loop could be exited.

i = 0
first = -1
while i < len(str) and first == -1: ## note new condition
	ch = str[i].upper()
	if ch == "A" or ch == "E" or ch == "I" or ch == "O" or ch == "U":
		first = i
	i += 1

if first == -1:
	 print("no vowels in word")
else:
    print("Vowel found at", first)

This loop condition correctly says that the loop continues while i is not at the end of the string and first is still -1. When first gets to be something that is not -1, a vowel has been found and the loop will exit OR the loop will exit when i reaches the end of the string.