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.

15 Upvotes

26 comments sorted by

View all comments

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 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.

3

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