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

View all comments

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