Python coding with loops! HELP!!
I really dont get how to loop with python can someoen help me??
So, here's a basic introduction to loops in Python:
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 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
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
And this pretty much sums up all you need to know for Python loops. I hope that helped!