1

I'm working through some examples from Treehouse via the Python course, and I'm having a hard time understanding the code below.

As far as I can tell we are looping through "You got this!". However, I'm not sure what the if statement is actually doing; can someone explain this to me?

for letter in "You got this!":
    if letter in "oh":
        print(letter)
4
  • this is not a good learning source if the example is only this. you should just print(letter) without the if to see what happens Commented Aug 7, 2018 at 2:25
  • What does it output? Try changing the strings and see how that changes the output
    – c2huc2hu
    Commented Aug 7, 2018 at 2:25
  • letter is going to be something like "Y", "o", "u", and so on. Do the checks "Y" in "oh" and "o" in "oh" make more sense?
    – Ry-
    Commented Aug 7, 2018 at 2:26
  • I didn't know you could compare a single character by using if letter in "oh" I assumed you that would match oh and not o || h
    – router7
    Commented Aug 7, 2018 at 2:29

5 Answers 5

1
for letter in "You got this!":

Will loop through every letter in the string:

first iteration: Y
second iteration: o
third iteration: u ....you get how this works

During each loop (or iteration), if the letter is either an 'o' or an 'h', it will print that letter.

1
  • Thanks that's a great explanation - I didn't know you could compare a single character by combining them in the if statement I assumed you would have to break it apart using an || statement
    – router7
    Commented Aug 7, 2018 at 2:30
0

So it runs through each letter in "you got this" and if the letter is "o" or "h" it prints it. I ran the code in my IDE and this is the conclusion I came to. My code printed o o h

0

letter in "oh" is really just a (IMHO misleading) shorthand for letter in ['o', 'h']

0

The comment are the explanations:

for letter in "You got this!": # Iterating trough `"You got this!"` (so 1st time `'Y'` 2nd time `'o'` 3rd time `'u'` ans so on...)
    if letter in "oh": # checking if the letter is `'o'` or `'h'`, if it is, print it, other wise go to the next one
        print(letter) # printing it

So that's why the output of this is:

o
o
h

See: https://www.tutorialspoint.com/python/python_for_loop.htm

0

First, you are iterating each character in the string "You got this!", that is the purpose of the for loop. This is something that you have clear, as you have stated.

Second, in this case, the if statement basically is saying:

If the current letter is in the string "oh" execute the following indented line.

Therefore, the statement print(letter) will be executed if the value of letter at the current iteration is either "o" or "h".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.