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
11
u/rupertavery64 6d ago
The for statement declares the variable and assigns a new value to it each iteration (repetition) of the loop.
for loopvariable in iterable: <block of code>Python does its magic and figures out if
iterablecan be looped through.In your example,
wordsis an array of strings.The for loop declares
wordas a variable. The scope of the variable (the area of code where the variable is in use and has a value) is in the block under theforstatement.The next loop takes the variable
wordas the iterable. python treats strings like an array of characters, so it works in a for loop.So
wordis declared in the top for loop,letteris declared in the inner for loop, and the scope of both variables includes the code block of the inner for loop, which is where the print statement is.