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!

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


Gabriel Ogbonnaya
Gabriel Ogbonnaya
1,701 Points

Explain this segment of code please: Python

for letter in secret_word: if letter in good_guesses: print(letter, end='') else: print('_',end='')

1 Answer

Mustafa Başaran
Mustafa Başaran
28,045 Points

Hi Gabriel, It would be handy to put your code in readable markdown format (Please see the markdown Cheatsheet link below)

I guess your question is something like this:

# I have a string variable to guess: "secret word"
secret_word = "secret word"

# I have a list of letters which I guess to be inside the variable secret_word
good_guesses = ["a", "b", "c", "d"]

# The for loop iterates over every letter in secret_word
for letter in secret_word: 

# In each iteration, if the letter is within the list, good_guesses
  if letter in good_guesses: 

# Then the for loop prints that letter. 
# end="" part within print() statement makes sure that we do not go the next line but continue printing horizontally
    print(letter, end="") 

# if the letter is not within the list items, good_guesses, it just prints '_'
    print('_', end="")

#For loop ends here.
#The below print statement outside the for loop goes to the next line. It looks better on the console when the program/for loop runs.

I hope that this is clear for you now.