Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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:

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:

# 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!