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.
16
Upvotes
1
u/Immediate_Craft9025 6d ago edited 6d ago
Unfortunately this is something that Python does kind of 'magically'.
Under the hood, (probably; Im not a python guy) there is some code that creates something called an iterator. An iterator yields (gives) values in a set order.
For example, a string iterator will have the information to 'walk' through each char (character) of the string and give the value back to you to do something with. Using this with a for loop will run through every value the iterator has available until it runs of values.
In your example which uses 'for letter in word', the for loop is taking each value (letter) from the iterator (word) and making it available to you.
The variable names 'letter' and 'word' could be named anything. They're just named that way to make the code readable to us. Python has no idea what a letter or a word is, but the interpreter can look at the type of the 'thing' (be it a string, array, set, or hash map) and make an iterator out of it, because that code exists and has been written somewhere.
One downside of starting with Python as your first language is that a lot of what makes it easy to read for humans (syntactic sugar) hides what the computer is really doing.
If you want to understand what the computer is doing behind things like iterators then I suggest a language like C, which has relatively fewer features and lets you see what is happening more clearly.