Ask coding questions

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

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

Commentshotnewtop
Icekit (62)

oh and plz upvote!!

Icekit (62)

I am doing for loops!

AmazingMech2418 (941)

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):
   print("Whatever")

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):
   print(counter)

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:
   print("whatever")

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 (62)

How do I close the loop??

slee8735 (3)

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

CodingCactus (3088)

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

https://how-to-python.codingcactus.repl.co/

CodingCactus (3088)

(it is a work in progress)

Icekit (62)

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 (3088)

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

mwilki7 (1111)

it all depends on what you want the loop to do