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 Functions and Looping For Loops

I did not understand anything in this video...

Can someone please please please explain what the difference is between while and for loops? I watched this video over and over and Craig loses me at the iterable-ness of strings. It's fun to run the same code he does and get the same result, but I don't understand what is going on.

1 Answer

A very simple explanation is this:

A While loop will run until the loop is broken or interrupted. A For loop will run until the object/objects it's iterating over are at it's final value.

For an example: You can use a While loop when you are trying to ask a user input...

correct_num = 5

while True:
    user_guess = input("Guess a number between 1 and 5: ")
    user_guess = int(user_guess)
    if user_guess != correct_num:
        continue
    else:
        exit()

The code above will run UNTIL the user_guess is right.

A For loop will just iterate over an object, For example:

list_one = [1, 2, 3, 4, 5]

for val in list_one:
    print(val)

# prints out: 1, 2, 3, 4, 5

This will print all values in the list until it has finished running through it.

I hope this helped!

Ok, this makes more sense now. Thank you!