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 Python Basics (2015) Logic in Python Loop

Loops in python are way to confusing. Can someone help?

Hello, I was recently watching the lesson Around and Around on the beginner's python course and they were talking about loops. I could not figure out what was going on and why they were doing it. For example...

for letter in "abcdefghijklmnopqrstuvwxyz"

print(letter)

This code you think would not be that hard to understand right? BUT IT IS!!! The problem is that they never defined letter as anything. So we can just pull variables out of thin air now? I don't know how this works and why. If anyone has a better explanation please tell me.

This was solved! Thanks

1 Answer

Hey Chase! Yes loops can be challengeing sometimes. What your talking about is called a "for loop" in python. What for loop does, is it loops through a list or string and look at each letter or integer. Now when defining a for loop we do it like this:

for (Your variable) in (Variable to loop thru): #Ignore parenthesis
    #Do something

So when you say for "something" You assigning whatever the loop is currently at, to that variable. Say we do this:

test = "abc"
for letter in test:
    print(letter)

were gonna get a, b, c as an output. This is because the for loop, goes thru each letter in the string test, assigns the letter its currently on to the variable "letter", and then in each iteration, prints what that letter currently is! I hope this clears up the confusion, but please feel free to write back if you need more help!