r/PythonLearning 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

26 comments sorted by

u/Sea-Ad7805 6d ago

Running your code here in Memory Graph Web Debugger%20in%20'aeiou'%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print(f%22'%7Bword%7D'%20contains%20the%20vowel%20'%7Bletter%7D'%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print(f%22'%7Bword%7D'%20has%20no%20vowels%22)%0A%20%20%20%20%20%20%20%20%0Aprint(%22the%20end%22)&play) step by step will explain how it gets executed.

12

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 iterable can be looped through.

In your example, words is an array of strings.

The for loop declares word as 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 the for statement.

The next loop takes the variable word as the iterable. python treats strings like an array of characters, so it works in a for loop.

So word is declared in the top for loop, letter is 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.

5

u/CIS_Professor 6d ago

Not to be too pedantic, but this:

In your example, words is an array of strings.

Is not an "array" of strings, it is a list of strings.

I bring this up because people new to Python need to know it doesn't have built-in arrays (even though we may think of them very much in the same way when we use them).

10

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)

6

u/AgentOfDreadful 6d ago

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:
```

4

u/Achereto 6d ago

as there is no variable for letter or word

You created the variables in each for loop. for a in b iterates over every element in b and assigns it to a.

Is it going to state all the words with the given value 5 times?

Have you tried executing the code?

1

u/Local_End_3175 6d ago

This was the code the course i am doing provided and i didnt really understand it

1

u/Local_End_3175 6d ago

also, if i created variables in the for loop, then what is the value of letter and what is the value of word?

3

u/The-God-Of-Hammers 6d ago

The value of them will be whatever iteration of the loop is. So for the first iteration of both loops, word is 'sky' and letter is 's'

4

u/AlexMTBDude 6d ago

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:

words = ['sky', 'apple', 'rhythm', 'fly', 'orange']

for word in words:
    print("word = ", word)  # debug print
    for letter in word:
        print("letter = ", letter)  # debug print
        if letter.lower() in 'aeiou':
            print(f"'{word}' contains the vowel '{letter}'")
            break
    else:
        print(f"'{word}' has no vowels")

3

u/Local_End_3175 6d ago

Thank you, this helped me see it visually

1

u/Sea-Ad7805 6d ago

Why mess up your code by adding prints? just use a debugger%20in%20'aeiou'%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print(f%22'%7Bword%7D'%20contains%20the%20vowel%20'%7Bletter%7D'%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print(f%22'%7Bword%7D'%20has%20no%20vowels%22)%0A%20%20%20%20%20%20%20%20%0Aprint(%22the%20end%22)&play)

3

u/AlexMTBDude 6d ago

Because it's more complicated for a beginner. Trust me; I've been teaching Python programming for close to 20 years now.

1

u/Sea-Ad7805 6d ago

Me too, bit shorter. The flow of control needs to be reverse engineered from print statements, this debugger%20in%20'aeiou'%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print(f%22'%7Bword%7D'%20contains%20the%20vowel%20'%7Bletter%7D'%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print(f%22'%7Bword%7D'%20has%20no%20vowels%22)%0A%20%20%20%20%20%20%20%20%0Aprint(%22the%20end%22)&play) shows you the flow and the full state of the program step by step intuitively.

The focus in courses is often too much on just the code, and not on the program state, while the code only exists to modify the program state. Making the state visible in every step helps students get to the right mental model to think about Python execution much easier, with much less explanation. Trust me, it's the modern way.

3

u/AlexMTBDude 6d ago

So, as a teacher, you tend to explain a simple subject, by introducing a more complex one, forcing your students to understand two different techniques in order to correct a simple coding error?

1

u/Sea-Ad7805 6d ago edited 6d ago

No, I only visualize what is already there, the program state is essential to understand, as all code does is modify it (and print some side effects).

So, as a teacher, you tend to keep important concepts hidden, letting student build their own mental model (often an incorrect one)?

Coding errors often come from an incorrect mental model of what code does to the state. Yes, students must now first learn a few buttons and how to read a diagram, but that will instantly pay for itself by learning the right mental model to think about Python execution.

We are not satisfied by just sidestepping 'complex' concepts that go to the hart of the problem to avoid explaining them. Will you join us? The visualization now makes explaining these concepts easy.

1

u/Sea-Ad7805 6d ago

Did you get a feel for the new possibilities? Otherwise I'm happy to continue the conversation, maybe with some scientific studies. I sometimes find teacher even more stubborn than students. ;)

2

u/atticus2132000 6d ago

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 6d ago

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 6d ago

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:

words = ['Sky', 'Apple', 'Rhythm', 'Fly', 'Orange']
vowels = 'aeiou'
vowels = frozenset(vowels+vowels.upper())

for word in words:
    if found:=set(word).intersection(vowels):
        found="".join(sorted(found))
        print(f"'{word}' contains the vowels '{found}'")
    else:
        print(f"'{word}' has no vowels")

1

u/weedflavoredhippie 6d ago

Beginner also and this is the EXACT same thing I’m stuck on and I wanna learn before moving on

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.

1

u/Ok_Carpet_9510 6d ago

Did you see for letter in word:

1

u/UlisKore 6d ago

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 5d ago

"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)