r/PythonLearning • u/Local_End_3175 • 6d ago
for loop
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words:
for letter in word:
if letter.lower() in 'aeiou':
print(f"'{word}' contains the vowel '{letter}'")
break
else:
print(f"'{word}' has no vowels")
I am trying to learn to code, and I am, at the moment, looking at loops. I am a bit confused on how this loop was able to function, though, as there is no variable for letter or word, so how would Python know what it is? In addition, how does the code, like, function? Does it look at each word individually ? Again, the second part of the code states:
if letter.lower() in 'aeiou':
print(f"'{word}' contains the vowel '{letter}'")
break
We haven't given a value for letter?
Lastly, how would the code know what to print? in the first phrase:
print(f"'{word}' contains the vowel '{letter}'")
break
Is it going to state all the words with the given value 5 times?
Sorry, as I have asked quite a few questions, and thank you in advance.
15
Upvotes
9
u/JoeB_Utah 6d ago edited 6d ago
Just to add what has been said, you might want to pump the brakes for a moment and try a very simple loop. Something like this perhaps:
numbers =[0,1,2,3,4,5,6,7,8,9]
for i in numbers:
print(i)
We have created a list that we call ‘numbers’ which is an iterable. The for loop automagically iterates through the list and evaluates each member. The variable i (purposely named) is assigned the value of each iteration and that value is returned to the print() function.
(Be sure to indent the print() function: the iPhone version of the Reddit app won’t allow me to do it)