Loops

"For" loops
For loops repeat over a sequence over and over. An example would be:

for x in range(10):

print(x)

* Prints the numbers 0 - 9*

for x in range(3,10):

print(x)

* Prints the numbers 3-9*

for x in range(3,10,2):

print(x)

* Prints 3, 5, 7, 9 - Missing the 2nd number each turn*

"While" loops
While loops repeat for as long as a condition is met. Example:

timer = 0

while timer < 10:

print(timer)

timer+=1    *Increments the timer variable by one*

* Prints 0-9 and then breaks out of the loop once "timer" has reached 10*

"Break" and "Continue" statements
break is used to exit a loop and continue is used to skip the current block and return to the looping statement.

if count >= 5:

break

* leaves the loop once count reaches 5 (within a loop)*

if x % 2 == 0:

continue

else:

print(x)

* A method to leave out all even numbers from a list being generated and only prints out the odds*

Continue to next lesson.