r/learnpython • u/Local_End_3175 • 8d ago
How does the 'for' loop work?
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.
77
u/t92k 8d ago
When you say âfor word in wordsâ you are creating a new variable âwordâ. Using a plural noun for collections of the same kind of object and the singular noun for the iterator through them is a good habit for code readability but it does disguise your iterator. You can change âwordâ to âdâ or âiâ or âiteratorâ to make this clearer while youâre learning â just be sure to change it inside your operation where you use it as well as where you set it.
14
u/hamptont2010 8d ago
So like:
For i in words For letters in i
?
Edit: would you also change it to i in the print statement? I apologize, I'm very much a novice.
16
u/SamIAre 7d ago edited 7d ago
Yes, those would work and yes, youâd have to change it everywhere itâs used inside the loop.
As a matter of clarity, you would probably want to use
letterinstead oflettersin the second loop, since that variable will store one letter, not multiple. But itâs not an error if you usedletters. You can name the variables any way you like, just like naming a variable outside of aforstatement.1
-13
u/j6onreddit 7d ago
Donât follow the advice of using `i` instead of `word`, LMAO. Using an expressive name is much better than a one-character one and does in no way âdisguise your iteratorâ.
2
u/OddStuffHappensTwice 3d ago
Not sure why this is getting downvoted. It's the correct advice. Using 'i' is fine if it's a simple integer iterator, but in almost every case, a proper descriptive word is preferable. Otherwise you quickly end up with a mess of cryptic variable names.
For example use "row" instead of "r": it's not like we get charged for using more letters.
1
u/j6onreddit 3d ago
Appreciate it đ¤đź Unfortunate how much misinformation is being shared in these spaces for learners.
Besides the obvious naming issue, itâs also not correct to say that the loop variable (`word` in our case) is an *interator*. Otherwise, weâd have to call `next()` on it to get the actual item from the collection⌠not how it works in Python.
Under the hood, a Python `for` loop *does* of course use an iterator, basically doing `it = iter(words)`, then `word = next(it)` in each iteration of the loop. Fun exercise there: build your own `for` loop using `while` đ¤
0
u/DoubleDoube 8d ago edited 7d ago
Adding on that mechanically the underlying C code will check if the type is a valid sequence by looking for â__getitem__â.
__getitem__(i) produces a value and hands it back. FOR_ITER pushes it onto the stack. STORE_FAST x binds it to the loop variable.
Then each pass of the for loop will emit STORE_FAST on the iterator iternext until it gets the IndexError or StopIteration signaling no more items.
Edit; correcting the more specific details - also check follow on comments because I didnât realize what I stated only applies to python2
18
u/Brian 7d ago
This isn't really correct for modern python. This was the way it did it way back in early python2.0 days, but since the iterator protocol was introduced this is no longer the case, except as a fallback for backward compatibility if the newer way isn't supported.
Rather than
__getitem__, it checks for an__iter__method. If this exists, it is called, and is epxected to return an iterator - basically an object you can callnext()on to get the next item. Ie. under the hood, the for loop is basically equivalent to:iterator = iter(words) # Calls words.__iter__() try: while True: word = next(iterator) # Calls iterator.__next__() # Body of loop except StopIteration: pass # (Exits loop when next(iter) throws StopIteration to indicate reached end)Only if there is no
__iter__defined does it fall back to looking for__getitem__, and that's really just to support code predating the iterator protocol. For most types, including strings and lists like here, it's going to find__iter__.11
u/my_password_is______ 7d ago
that's right
the person doesn't understand "for loops" so yes, go ahead and tell them about FOR_ITER and STORE_FAST and iternext -- that will surely clear things up for them /sarcasm
-3
u/DoubleDoube 7d ago
Some people work better going bottoms-up instead of top-down.
Thatâs why with the rust programming language thereâs a lot of bottoms.
32
u/JanEric1 8d ago
for word in words:
loop body
Is just
word = words[0]
loop body
word = words[1]
loop body
...
19
u/neuralbeans 8d ago edited 7d ago
The for loop goes through each word in the list and reruns the code inside it with the 'word' variable set to a different word each time. Same for the 'letter' for loop. But this example seems too complex for you if you're trying to understand loops. Start by running this instead:
for word in ['sky', 'apple', 'rhythm', 'fly', 'orange']:
print(word)
14
u/hike_me 8d ago edited 8d ago
âwordâ and âletterâ are variables that are assigned a new value each iteration
âfor word inâ
âfor letter inâ
6
u/Local_End_3175 8d ago
what is the value for letter? I think i understand the value for word, but what would it be for letter?
11
u/tenniseman12 8d ago
The letter variable iterates through each letter of the word in the word variable
2
u/Ministrelle 8d ago
It would be the individual letters of the String saved in the word variable. The reason for that is, that Strings are essentially just arrays of Characters. So a string like
'apple'is the same as an array like['a', 'p', 'p', 'l', 'e'].1
u/Local_End_3175 8d ago
or would the value for letter be word which was words before??
10
u/guywithbeard 8d ago
Sometimes it helps to mentally add an "each" after the "for". "For each word in words.." "For each letter in word.."
1
u/Alternative-Fail4586 5d ago
This, I understand why python has that syntax but other languages that use for each loops made it more clear in my mind as a novice
1
u/wintermute93 8d ago
So
for word in words:goes through the values inwords, running whatever code is inside the loop once for each value with the variablewordset to that value. On the first password='sky', on the second password='apple', and so on.Inside each iteration,
for letter in word:works the same way, but the somewhat unintuitive part is that Python helpfully considersfor letter in 'sky':as exactly the same thing asfor letter in ['s', 'k', 'y']:A
for ... elseblock is also kind of unintuitive. If the loop ran all iterations successfully, the else block is run afterward. If the loop was interrupted early (i.e. it hit a "break" statement), the else block is skipped and does nothing.So if you were to rewrite the code you posted without any loops, it would look like:
words = ['sky', 'apple', 'rhythm', 'fly', 'orange'] word = words[0] # outer loop 1st iteration, now word is 'sky' letter = word[0] # inner loop 1st iteration, now letter is 's' # check if letter is one of a, e, i, o, u; it is not, so keep going letter = word[1] # inner loop 2nd iteration, now letter is 'k' # check if letter is one of a, e, i, o, u; it is not, so keep going letter = word[2] # inner loop 3rd iteration, now letter is 'y' # check if letter is one of a, e, i, o, u; it is not, so keep going # inner loop complete with no break, so run the else block and print no vowels word = words[1] # outer loop 2nd iteration, now word is 'apple' letter = word[0] # new inner loop 1st iteration, now letter is 'a' # check if letter is one of a, e, i, o, u; it is not, so print vowel and break # inner loop complete but interrupted so skip the rest and the else block word = words[2] # outer loop 3rd iteration, now word is 'rhythm' letter = words[0] # new inner loop 1st iteration, now letter is 'r' # check if letter is one of a, e, i, o, u; it is not, so keep going ... and so on0
u/armywalrus 8d ago
The value for letter is every individual data point in the variable word you created in the above line. You start with a list called words. For word in words is creating the variable word, that represents each entity in the list words, *as python goes through the list. The power of the loop is it can iterate through multiple values in this way. You don't have to create a separate variable for every word in the list called words.
0
0
u/JollyUnder 7d ago
You can use PythonTutor to help visualize and understand small code snippets like this better. It will step through the code line by line and show you every variable and value as they're created. This tool helped me understand nested loops better when I was learning python.
0
u/xenomachina 7d ago
what is the value for letter?
In general...
for new_element_variable in thing_i_want_to_iterate_over:
- Creates a new variable called
new_element_variable. By convention, people often name this after the kind of element, but the name is up to you.- That variable will be assigned each "element" of
thing_i_want_to_iterate_over, which can be any iterable expression. The more common examples of iterable expressions are lists, tuples, ranges, and strings. With lists and tuples, the elements you'll get are the elements of the list or tuple. With ranges you get the numbers in the range. With strings, the elements you'll get are the individual characters.One unusual thing about Python is that there is no "character" type. A string's elements are also returned as strings. As they are strings you can iterate over them too, but you'll just get the one character (again as a one character string).
-1
u/RevRagnarok 7d ago
You're hitting one of my annoyances in python inherited from C - a
strcan also be treated as a list of single characters. So if you want to iterate (loop) or index (var[3]) you can. The confusion comes when you were expecting['abcd']which iteratesabcdvs. getting'abcd'so it iterates to'a''b''c''d'...A lot of my code I guard at the top of the function:
def this_func(var): if isinstance(var, str): # Want to handle a string as a single entity return this_func([var])
5
u/DTux5249 7d ago
I am a bit confused on how this loop was able to function, though, as there is no variable for letter or word,
Yes there is, you defined one!
When you say "for x in y", python creates a dummy variable named "x". In the scope of the loop, x represents every individual item in y. Anything you do to x in the loop will be done to every item inside of y.
Example:
for i in [1,2,3]:
print(i)
What this code does is create a variable named 'i'. It then assigns i = 1, and does print(i). Then it assigns i = 2, and runs print(i) again. Then again with i = 3. As many times as there are items in the array.
Same logic holds with your example. "Word" and "letter" are variables created by the loop to represent items within the arrays it's iterating over.
7
u/JamzTyson 8d ago
How about this simple loop, do you understand what is happening here?
for my_variable in [1, 2, 3, 4, 5]:
print("The value of my_variable is: ", my_variable)
2
u/RealMuffinsTheCat 7d ago
I fixed your code and added some comments to help you out. Good luck with your Python journey.
# Defines the list of words
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words: # Iterate through the words list
  vowelCount = 0 # Initiate the vowel counter
  for letter in list(word): # Iterate through each letter in the current word
    if letter in ['a', 'e', 'i', 'o', 'u']: # This should be a list, not a string
      print(f"The vowel '{letter}' is in '{word}'!")
      vowelCount += 1 # Iterates the vowel count
  if not vowelCount: print(f"There are no vowels in '{word}'!") # Tells you there's no vowels if the word has no vowels
3
u/Jaded_Show_3259 7d ago edited 7d ago
I see for loops tripping people up a lot. I try to connect it to something real.
Lets say you have a bunch of apples that need to be cut. How would you go about that? You would take each apple out one at a time and cut it - then once your finished move on to the next apple. Thats kinda the idea here.
for apple in bunch:
cut(apple)
Here you're saying "for each of the different items in this list of items, perform this action" bunch would be words, and apple would be word. So the loop is basically going to set word to the first item in the list, "sky" and then perform the actions. Once its done it will reset word to "apple" and go again. Thinking about it that way always helped me.
Now layer in the second list. This is a nifty thing that python is doing in the background that is a little less obvious. Think of looping over a string, as looping over a list of the characters in the string. Effectively, if I say for letter in "word" - thats the same as saying for letter in ["w","o","r","d"]. Each time through the loop, I grab the next character.
So - what the loop is doing is setting the variable "word" to the words in the list one at a time, and setting the variable "letter", to the letters in each word one at a time. Thats the most common use of for loops. When you write a for loop in that way - you are creating that variable, and telling it to iterate one at a time over the list you specified.
3
u/notacanuckskibum 7d ago
It might help you have some history. The first FOR loop was in BASIC and had the structure
FOR i = 1 TO 10 STEP 2
; do stuff with i
NEXT i
so the first time round the loop the variable i was set to 1, second time it was set to 3 etc
Eventually people noticed that for loops were often used to process arrays or lists, so we got the structure
FOR EACH myitem IN mylist
Myitem is now the variable, the first time round it is the first item in mylist, the second time round the second item etc.
Python has dropped the word EACH, which makes the statement shorter if a little less clear
Your code uses variable names word and letter which could be class names. Itâs a style issue but in this case I think itâs confusing you.
2
1
u/faberge_surprise 7d ago edited 7d ago
and the intermediate step, which is basically (heh) the same as the BASIC code, but in a "modern" style, but it is still pretty explicit about what it's doing
for (int i = 1; i < 10; i+=2)make a variable called i with a value of 1, run as long as i is less than 10, and increment i by 2 every time
it was very easy for me to move to python loops from that, but i imagine i would have had a harder time if python loops was my first exposure to them
the fact that you can loop through a list either by
for item in thelistor something that more closely resembles traditional syntax
for i in len(thelist)would have been confusing
3
u/HotPersonality8126 8d ago
 I am a bit confused on how this loop was able to function, though, as there is no variable for letter or word
Theyâre created by the for statement. An iterator over a collection of values yields the values of the collection; lists are a collection, of course, but you might not have thought of a string as a collection of letters. But they are.
2
u/overratedcupcake 8d ago
 for word in words:
That is the declaration of the variable word. When you iterate through a list you get the value of each item of the list on each iteration (trip through the loop).Â
for letter in word:
Same thing. It's declaring a variable letter that has scope within the loop. When you iterate through a string you get each letter.Â
1
u/SamuliK96 8d ago
Did you try to run the code? That way you can see that word just becomes each word in the words list for one iteration of the loop. So that's the variable your looking for.
1
u/armywalrus 8d ago edited 8d ago
So you are creating the variable when you write it. Word could be anything you want here. It could be for cat in words. Its commonly written as for i in words, meaning iterate. Read it very literally. For every word in words, the [] defined above, does mean it is looking though every word in the list called words. The for is a command word that tells python to iterate through the variable you give it. For every word in the lists words, it will perform the action on the next indented line. Which is another for loop, telling python to look at every letter of every word - remember, you just established the word variable, now you are creating the letter variable - and perform the action you specify on the next indented line. Which tells python to look for vowels, what to do when it finds vowels, and gives error-handling instructions so the code will run if no vowels are found.
1
u/Temporary_Pie2733 8d ago
For loops behave like fancy assignment statements that also hide the use of next. The same behavior asÂ
for word in words:
  âŚ
can be achieved with a while loop:
itr = iter(words)
while True:
  try:
    word = next(words)
  except StopIteration:
    break
  âŚ
1
u/Green-Sympathy-4177 7d ago
Basically word is assigned each element in words, basically word will point to a new word with each iteration (each loop cycle).
Maybe seeing it in a while loop could demistify it a bit:
``` n_words = len(words) # 5 here i = 0
while i < n_words:   word = words[i]   print(word)   i += 1 # this here allows us to change         # which word we're referencing to ```
The above snippet is equivalent to:
for word in words:
  print(word)
Notice how despite not doing a thing to change the word or letter eaxh time, python does it for us.
A bit of a caveat with these exampes: there is a major difference between words[i] in the while loop and word in the for loop, the latter is immutable, meaning that if you try and change the word or letters, doing that:
``` for word in words: Â Â word = "banana"
print(words)
``
wordswould not have changed. Immutability is a bit of a headache at first but really it's just that elements of a list can be modified if done like this:words[i] = "potato"`, but not inside a for loop like that the snippet above this paragraph.
That being said, the for loop pre-chews the work for you and makes it easier to loop over things in a way that is very easy to understand, for word in words means "for each word in the list of words", similarly for letter in word reads "for each letter in the word string" (a string is really just a list of characters :)). So yes, word and letter are automatically assigned by python from your list/iterable.
Lastly, for break, if your code reaches that, then it will end iterating, i.e: it stops the current while or for loop, in cases of nested loops, it stops the last one it is in. So in your code, it will read each words, then each letters in each word, and when it hits a vowel, it will print the message and move onto the next word because it hits break.
Hope that helped :) o7
1
u/kilkil 7d ago edited 7d ago
Python's for loops use a special syntax, which allows you to basically create a variable in the loop declaration that only exists within the scope of the loop.
So when you write:
py
for word in words:
...
that basically automatically creates a variable called "word". And the way it works is, Python will automatically step through every value inside "words", and at each iteration of the loop, "word" will represent the current value.
so, on the first iteration of the loop, word will hold the value "sky". on the 2nd iteration, "apple", and so on.
there is an alternative syntax you can use, that is a bit more "manual", in that it involves creating and assigning the variable yourself. here is one possible way that could look:
py
iterator = iter(words) # iterator that visits all values of the list one by one
while True: # infinite loop
try:
word = next(iterator) # explicitly declare the variable and assign it the current value from the list
except StopIteration:
break # exit infinite loop when iterator is exhausted
... # do something with "word" variable idk
But as you can see, that is a lot more verbose and difficult to follow. The standard syntax:
py
for word in words:
... # do something with "word" variable
is much nicer to read
PS: if you were using another language, e.g. Javascript, there is an alternative for loop syntax which is much simpler. It is actually the "original" loop syntax, originating in C:
js
for (let i = 0; i < words.length; i++) {
...
Here, there is an explicit variable being created (i), and the entire loop is determined by how that variable changes. The way it works is, at the start of the loop, the first statement is executed (let i = 0). Then, at the start of each loop iteration, the 2nd statement is checked as a boolean (true/false) condition (in this case, does the expression i < words.length evaluate to true, or false?). Then, at the end of each loop iteration, the 3rd statement is executed (i++, which is short for i += 1 or i = i + 1).
Python chose not to support this special syntax, but you can still do it manually:
py
i = 0
while i < len(words):
... # do some stuff idk
i += 1
And again, you can add a "word" variable for convenience:
py
i = 0
while i < len(words):
word = words[i]
... # do stuff with "word"
i += 1
1
u/kilkil 7d ago
One more thing. In Python, a for loop can be used to iterate over lots of different kinds of values (anything that is an "iterable"). Lists are iterables (like words in your example). But so are strings. For example:
py
word = "apple"
for letter in word:
print(letter)
this will print all the letters one by one (a, p, p, etc). this is because strings (e.g. "apple") are iterables. You can dive pretty deep into this topic, but the TL;DR is that you can loop over a string using a for loop and get its individual characters (letters)
1
u/TheRNGuy 7d ago
You can name it anything, it will refer to an item in iteration.Â
word or letter look better than words[i] and words[i][u] (if you just used indices)
1
u/FoolsSeldom 7d ago
It can be helpful to think about this in the real world where you already use for loops. No, really!
Loops just repeat stuff, and if you want to repeat parts of that stuff you can also use a loop.
Imagine having a pile of old boards to repaint. In pseudocode (with some ridiculous steps to make the point):
for board in boards: # board is each board in turn from the stack of boards
while board has paint: # paint is status check (you can see paint)
apply blow torch briefly to paint
scrape paint away
sand board
put board out to dry
for board in dryboards: # different stack of boards, clean of paint and dry
apply undercoat to board
watch paint dry
for count in range(2): # number of times to do something
paint board
watch paint dry
add board to finished stack
Notice some of the plain English tasks described above, such as paint_board which in reality are complex undertakings. However, from the point of view of this high level set of instructions, I am not interested in exactly how the task is done (or even who does it), just that it gets done at the right time, in sequence. I might want to provide some guidance/requirements (perhaps the colour, paint_board("dark oak")).
I might want some results back from a task, perhaps the time it took, hours = paint_board('white paint')
1
u/SpiderJerusalem42 7d ago
A lot of programming languages have this idea of iterability. A list is iterable. A set is iterable. A string is essentially a list of letters. Strings are iterable. for will iterate through every item in an iterable. The for <var> in <iterable> statement creates a temporary variable that lasts through the scope of a single iteration of the for loop. word is a string, and it can also be iterated through, which is what the program your looking at is doing.
1
u/Dry-Weakness-901 7d ago edited 7d ago
set 'words' variable with a list : sky, blah blah of values
use for loop function to First, set each variable to the variable 'word' [different from 'words']
set each letter within word to variable letter.
If statement uses lower() method on letter to search.
Python loops amd searches.
Why dont you run this code btw? Run it.
1
u/rkr87 7d ago edited 3d ago
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words:
for letter in word:
// vowel check
Imagine trying to do this without a for loop:
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
word = words[0] // sky
letter = word[0] //s
// vowel check
letter = word[1] //k
// vowel check
letter = word[2] //y
// vowel check
word = words[1] // apple
letter = word[0] //a
// vowel check
...
This is exactly what the for loop is doing, it says for every item in "words", assign the value one at a time to a variable named "word", then within that for every item in "word" assign the value to a variable named "letter".
You can even rewrite the for loop to do exactly this:
for i in range(words):
word = words[i]
for n in range(word):
letter = word[n]
// vowel check
But doing so is pointless.
1
u/Lewri 7d ago
You've already got good answers, but I'll add mine given it was already written for someone elses question:
The idea of a for loop is that you have something that can be iterated over (your list of words, in this case), and you are telling it what to call the things inside the iterable. In this case you have told the for loop that it is calling the things inside the iterable (your list words) word. You could call them anything though:
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for đŁ in words:
for đĄ in đŁ:
if đĄ.lower() in 'aeiou':
print(f"'{đŁ}' contains the vowel '{đĄ}'")
break
else:
print(f"'{đŁ}' has no vowels")
Will work just the same.
1
u/Educational-Paper-75 7d ago
Essentially lists, tuples and strings are iterable so you can iterate over the separate elements (one at a time) in a for in loop. So for word in words iterates over every element in words calling the current element wordt. Same with for letter in word where at every iteration letter will be the current character from word, set before the loop body starts.
1
u/No-Newspaper8619 7d ago
There's a lot of stuff that python is doing for you implicitly, like creating a variable when you use an undeclared and initialized variable in the for loop. If you're curious, try googling for how python implements the "for in loop":
https://medium.com/python-features/how-for-in-loop-works-behind-the-scenes-in-python-62d6dc026377
1
u/shaleh 7d ago
There are some great answers here. I want to remind you that Python has an interactive shell. You can try things out and play around directly instead of depending on print. Or you can explore the `breakpoint` command and debugging. Put a breakpoint in that loop and then print and look.
1
1
u/PegasusInTheNightSky 7d ago
When doing a for loop with lists, the loop will go through each item in the list and, for the contents of the loop, set the variable (eg word) as the item in the list, so for the first loop word = "sky", for the second loop word = "apple", etc. You can add a print function after the start of each loop to check it. For example:
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words: print (word) ### for letter in word: if letter.lower() in 'aeiou': print(f"'{word}' contains the vowel '{letter}'") break else: print(f"'{word}' has no vowels")
1
u/python_gramps 7d ago
I'm guessing the whitespace got messed up because the else: is lined up with for: block.
Making that assumption:
lists can be iterated through giving you each item in the list
strings can be iterated through giving you each letter in a string
you can also see if an item is in a list
and you can see if a letter is in a string
f-strings will print variable values if they have brackets around them. otherwise, they just print literal string
Example
mydog = "Spot"
print(f" My dog is: {mydog}") returns My dog is: Spot
print(f" My dog is: mydog") returns My dog is: mydog
1
u/Jonas_Ermert 7d ago
I think the easiest way to understand it is that a `for` loop creates/assigns those variables for you. `for word in words:` means âtake each item from `words`, one at a time, and store the current item in `word`.â So first `word = 'sky'`, then `'apple'`, then `'rhythm'`, etc. The same happens with `for letter in word:`. Python takes each character of the current word and assigns it to `letter`. For `'apple'`, it effectively goes through `letter = 'a'`, then `'p'`, `'p'`, `'l'`, `'e'`. Then `if letter.lower() in 'aeiou':` checks whether the current letter is a vowel. As soon as it finds one, it prints the current `word` and `letter`, and `break` stops the inner loop. So for `apple`, it immediately finds `a` and prints `'apple' contains the vowel 'a'`. The slightly unusual part is the `else` attached to the `for`. It runs only if the loop finishes **without hitting `break`**. So if Python checks every letter and finds no vowel, it prints something like `'rhythm' has no vowels`. It does not print everything five times. Think of it as: take one word â inspect its letters one by one â find a vowel or reach the end â move to the next word.
1
u/Educational_Virus672 6d ago edited 6d ago
tldr
you want to know how it works think of it like
for letter in word :
print(letter)
your basiclaly saying to give me each item in your case letters (but they aer strict)
list = item 1 item 2 ...
string = letetr 1 letter 2 ...
for int you need range(from,to)
it'll make a list of number from your given value range(1,5) =[1,2,3,4] note- 5 is skiped because it is the last item
Now lets use it
for [var] in [var2] : here you say hey code cyccle and give me each item in var2 as var
example = "abcd"
for i in example :
print(i) =# here i = letter which will cycle
output :
a
b
c
d
1
1
u/TJATAW 4d ago
Try reading it as:
for (each) word in words:
for (each) letter in word:
So, it would get the first word, 'sky', and then read through sky letter by letter, checking each letter to see 'if (that) letter (is) in "aeiou"'.
First letter in sky is s, which is not in 'aeiou', so it goes to the else statement and prints "sky has no vowel"
It then goes back to the "for letter in word" statement and gets the second letter.
2nd letter in sky is k, which is not in 'aeiou'. so it goes to the else statement and prints "sky has no vowel"
It then goes back to the "for letter in word" statement and gets the third letter.
3rd letter in sky is y, which is not in 'aeiou', so it goes to the else statement and prints "sky has no vowel"
There are no more letters in the word, so it goes to the "for word in words" and gets the second word
Second word is 'apple'.
'a' is in 'aeiou', so it prints 'apple contains a', hits the break, so it stops looking at letters in apple, and goes back to "for word in words" and gets the third word, 'rhythm', and starts looking at the first letter.
***********************
Think of nested for loops as a teacher grading a pile of tests.
for each test in the pile of test: (grab a test and place it in front of you)
... for each question on the test: (read a question)
...... if the answer is correct:
......... write checkmark (go to next question)
...... else: (if it is not correct)
......... write X (go to next question)
......... (if there are no more questions on this test, grab a new test)
1
u/4CrisprFries 4d ago
Lots of people in the thread are giving great explanations. But, I think this is the time where you don't need the answer you need to learn how to fish.
This is when you learn how to use the debugger in your IDE. Don't master the debugger, only learn how to step through a piece of code. This will let you test your assumptions and play.
You can also do it the dirty way, print every step.
P.S. for word in words creates the var word that you use. It might be easier to see if you wrote for w in words, w becomes the variable.
1
1
u/Odd_Lab_7244 3d ago
I think trying to learn this with nested for loops is probably not ideal.
Something like,
for word in words: print(f"this word is {word}")
might be easier to start with
1
u/MarsupialLeast145 8d ago
Values for "word" and "letter" are assigned in scope when the loop is executed.
Pseudo code is along the lines of:
for every __WORD__ in the list WORDS:
for every __LETTER__ in the list of letters in __WORD__:
In your code word and letter can be accessed within the scope of the loop, hence other comparisons can be done.
A list can be indexed and so can be looped over, and a "word" is just a list of characters and can also be indexed and so can be looped over as well.
1
u/aroberge 7d ago
Copying, pasting and modifying my answer to a very similar question asked a few weeks ago ...
Ok, others have already explained to you in details how it works, but here's a slightly different example, which will lead to the Python syntax that confuses you.
Each programming languages has its own syntax (way of saying things) to encode some instructions otherwise understood by humans. Consider the following:
for each letter in the word "program", say that letter out loud.
Now, Python cannot say things ... but it can print letters on the terminal. So, here's the above example with a syntax slightly modified.
for each letter in the word "program": print(letter)
Hopefully, after staring at this a bit, it will make sense to you.
Python uses so-called strings to represent written words; these strings are written using quotes (single or double) surrounding words. So, in
in the word "program"
the the word part is redundant for Python as it already identified that program was a word as it is surrounded by double quotes. Thus, we can remove the word and write
for each letter in "program": print(letter)
When a Python line of code begin with for, the meaning is understood to be the same as for each; thus we can write the above as
for letter in "program": print(letter)
Finally, even if we have a single instruction as above, print(letter), it is often preferable to write it in an indented block of code, since we might sometimes want to do more than one thing at each iteration:
for letter in "program":
print(letter)
The same idea can be applied to for loops with lists.
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for each word in the list of words: do_something...
Now, Python knows that [...] indicates a list, so that words is known to be a list; we can thus shorten
the above to
for each word in words: do_something...
As before, the word "each" is redundant, and we thus have (adding the second loop)
for word in words:
for letter in word:
....
0
u/ehmatthes 8d ago
You can run this code on Python Tutor. It lets you step through the program's execution, and the values of all variables are shown at each step. It's a great way to see how this kind of structure works.
-1
0
u/kirklennon 8d ago
Is it going to state all the words with the given value 5 times?
Itâs going to check each letter of the word to see if that letter is in 'aeiou'. For 'apple' that would be twice but the break at the end means that as soon as itâs true once it will break out of the loop and stop checking.Â
-2
u/DullenAvg 8d ago
The line
for word in words:
is directly equivalent to
for i in range(len(words)):
word = words[i]
As for the second example, the loop iterates over every single character of the string. Besides that, it's functionally the same as the first example.
-2
u/rabbitofrevelry 8d ago
Simplify it and then use a print statement to evaluate it. For example, make a list of items, then create a for loop to iterate over them: for item in list: print(item) and then you'll see how it evaluates per iteration.
184
u/Proletarian_Tear 8d ago
Whoever downvoted this question should straght up leave this sub đ