Ask coding questions

← Back to all posts
Python coding with loops! HELP!!
Icekit (63)

I really dont get how to loop with python can someoen help me??

CodingCactus (4195)

I am currently working on a python tutorial, maybe have a look at it:

CodingCactus (4195)

(it is a work in progress)

Icekit (63)

your a pretty good coder! I have looked at a lot of your stuff! though I could help you in python tutle that cactus!:)@CodingCactus

CodingCactus (4195)

@Icekit oh, yeh, I forgot about that cactus lol! I'm not too good at turtle :(

Icekit (63)

oh and plz upvote!!

Icekit (63)

I am doing for loops!

AmazingMech2418 (1039)

So, here's a basic introduction to loops in Python:

While Loops

If you want to do something until a condition is met or while a condition remains true, you use a while loop. However, it only natively supports the "while a condition remains true". For example, this code will loop while the condition condition is true.

while condition:
   print("I don't know what to make this do. This is just an example")

To loop until condition is true, just use

while not(condition):
   print("I don't know what to make this do. This is just an example")

For Loops

For loops are more complicated than while loops, but they do something else to make a counter variable useful.

Range For Loops

If you want to repeat something x times, you can use

for counter in range(x):

However, if you want to count from 1 to 10, you will have to specify a starting parameter which will be 1 in this case. However, for the ending variable, you will have to add 1, so you have 11 instead.

for counter in range(1,11):

You can also specify how much the counter will change, similar to how you did in this repl, by adding a step parameter, following the format range(start,end,step).

Iterables (normally lists, tuples, strings, or dictionaries)

You can also use Python to loop through an iterable object such as a list, tuple, string, or dictionary. In a list or tuple, the counter variable will be an item of the list/tuple. In a string, it will be a character. In a dictionary, it will be a key in that dictionary. Using the iterable object as iterable, you can use

for counter in iterable:

Break and Continue

If you want to continue to the next iteration, skipping content, use the continue keyword. If you want to exit a loop before a given condition is met, use break.

And this pretty much sums up all you need to know for Python loops. I hope that helped!

Icekit (63)

How do I close the loop??

slee8735 (4)

You can put in 'break;' in the loop after you're done using [email protected]

mwilki7 (1134)

it all depends on what you want the loop to do