Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

rudy19
seal-mask
.a{fill-rule:evenodd;}techdegree
rudy19
Python Web Development Techdegree Student 507 Points

How does "if" work in a for loop?

 for letter in "You got this"
     if letter in "oh":
          print(letter)

How is there two O's when there is only one in "oh"

The code says for each letter in "You got this!"

Only IF there's a letter in "oh"? (also doesn't make any sense to me)

2 Answers

Aananya Vyas
Aananya Vyas
20,157 Points

Hi Rudy! The answer above this explains the concept very well^ thankyou [https://teamtreehouse.com/davevarmutant] also to make the logic simple you could understand it as- in the string (given to search)- "You got this" we are supposed to find the occurrence of an "oh" anywhere. IN ORDER. so imagine there was "you got this" written on a chalkboard, and you have to find if you can make an"oh" out of it, well yes you can. delete all except an o and an h that occur in order

Its like "art" in "earth" I hope it helps to further clarify the logic up! let me know if I can help anymore happy coding :D

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Hello rudy19,

The for loop is looping over the iteratable string "You got this" and each time through the value from the string is in the variable letter. So, the if statement is checking each letter (including the spaces) to see if it is in the string "oh" - so any o's or h's will be true.

The easiest way to see this is by adding a print statement before the if like below:

for letter in "You got this":
     print('before the if - letter is -->' + letter)
     if letter in "oh":
          print(letter)

The output is:

before the if - letter is -->Y
before the if - letter is -->o
o
before the if - letter is -->u
before the if - letter is --> 
before the if - letter is -->g
before the if - letter is -->o
o
before the if - letter is -->t
before the if - letter is --> 
before the if - letter is -->t
before the if - letter is -->h
h
before the if - letter is -->i
before the if - letter is -->s

Does that help?

rudy19
seal-mask
.a{fill-rule:evenodd;}techdegree
rudy19
Python Web Development Techdegree Student 507 Points

Thanks for the in-depth answer. The first sentence has me confused tho. Other than that, the rest made sense ☻