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 Collections (Retired) Dictionaries Dictionary Iteration

Emmet Lowry
Emmet Lowry
10,196 Points

Dont understand for loops

Could someone explain for and while loops i dont really get what the do thanks.

2 Answers

Hi emmet.

For loops are loops that are defined and While loops tend to keep running until a condition breaks the loop. for example if you wanted a loop that went around 20 times you would write somthing like this.

for x in range(1,21):
    print(x)

// example of a while loop
while True:
    myinput=input("What is your name [q] to quit  >>  ")
    if myinput=="quit":
        break;

the while loop will keep running till the the user enters the word quit.

And by defined, you mean: with a defined number of iterations/cycles.

Hi Iain

yes by defined that's what I was getting at.

Emmet Lowry
Emmet Lowry
10,196 Points

Can you name the for loop anything in the x area could you write anything

Yes in the for loop you can replace x for anything.

for whatever in range(1,21):
    print(whatever)