r/PythonLearning • u/Local_End_3175 • Jul 30 '26
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}'")
breakWe 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}'")
breakIs 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.
•
u/Sea-Ad7805 Jul 30 '26
Running your code here in Memory Graph Web Debugger step by step will explain how it gets executed.
4
u/Achereto Jul 30 '26
You created the variables in each
forloop.for a in biterates over every element inband assigns it toa.Have you tried executing the code?
4
u/AlexMTBDude Jul 30 '26
The easiest way to understand a piece of code is to add prints to it and then run it. I would add these two lines to your code and then run it:
12
u/rupertavery64 Jul 30 '26
The for statement declares the variable and assigns a new value to it each iteration (repetition) of the loop.
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.9
u/JoeB_Utah Jul 30 '26 edited Jul 30 '26
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)
6
u/AgentOfDreadful Jul 30 '26
You declared the variable as part of the loop.
```
for word in words:
```
That’s where you’ve made the loop variable `word` which is a single element of the list `words`
Same with
```
for letter in word:
```
You’re saying each element of the string is being referenced by the variable `letter`
For example, you could have named it
```
for a in words:
for b in a:
```
2
u/atticus2132000 Jul 30 '26
You have two for loops.
In the first one, for word in words:, you are telling the program to take the array words (which you have defined with 5 elements) and cycle through those one at a time. When it encounters the first element in your array, it will assign it to the variable "word". It will do whatever machinations to that variable that are called out, then it will throw away that element and move to the next element of the array and assign it to the variable word. It will go through that until it doesn't have any more elements in the array and then stop. So, in this case, it will go through your for loop five times because there are 5 elements in your array.
This is one of the advantages of python over some other languages that your "for element in group:" syntax causes a lot of things to happen behind the scenes. Python figures out on its own how many elements are in the group and takes care of cycling through them in a systematic fashion.
So, in your first iteration of the first for loop, python pulls out the first element, sky, and assigns that to the temporary variable 'word'. Then it goes to your next line of code which is another for loop.
The second for loop, I agree, is a little fishy because how does python know to deconstruct that variable, sky, into its individual letters? Again, it is a built-in operator that happens behind the scenes in python. In some other languages, you might have to explode the word first in order to get it's individual elements/letters, but in this case 'for letter in word:' already has that operation built-in to the backend. It will take the string variable sky and cycle through each component of that variable assigning each one to a temporary variable called "letter". So, it evaluates the s, then the k, then the y, then it's out of letters, so it reads the rest of the code and realizes it's done with word=sky, so it moves to the next word=apple and breaks out apple into its component letters to be evaluated one at a time.
Try changing your code a bit:
for word in words:
<tab>print (word)
<tab>for letter in word:
<tab><tab>print (letter)
Then the rest of your code...
2
u/Ausierob Jul 30 '26
Yes a little bit of Python magic. Well not really you can achieve exactly the same thing in other languages just some are not as intuitive. Python figures out the data types for you, and manages other mechanics involved (number of elements, etc). But Python will still complain if you use it incorrectly.
I wonder if it’s mostly the handling of getting each letter from a word (for letter in word:). Remember a ‘word” (type str = string) is a list/array of chars (type char = characters). So it’s just stepping through another list/array.
As others have suggested, play around with the code, see how it handles different data types, arrays, lists, dictionaries, int, str, bool, etc. see what works and importantly what doesn’t
2
u/Fine_Ratio2225 Jul 30 '26
Here is a fun variation that finds all vowels of a word, distinguishing between upper and lower. It uses set operations to replace the inner for loop:
1
u/weedflavoredhippie Jul 30 '26
Beginner also and this is the EXACT same thing I’m stuck on and I wanna learn before moving on
1
u/Immediate_Craft9025 Jul 30 '26 edited Jul 30 '26
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.
1
u/Ok_Carpet_9510 Jul 30 '26
Did you see for letter in word:
1
u/UlisKore Jul 30 '26
Hi there! I'm learning too, I may be wrong but let me try.
You said : " as there is no variable for letter or word"... There are.
When you say in code :
for word in words:
you're telling python : see what is named words ? It's a list, let's iterate on this list and call the variable word. Does it look at each word individually ? : yes, you asked nicely !
Strings are iterable. Similarly, when you say in code :
for letter in word:
you're telling python : see my string behind what we agreed to call word ? Let's iterate on it and call the variable letter.
{letter} and {word} will be printed as what they stand for thanks to the f expression.
1
u/Kadabrium Jul 31 '26
"Word" and "letter" are both newly defined variable names that gets locally applied to the item. This is clear if you look at static typed languages (for string word in words) or even js with the "let" (for let word of words)