Loops

Loops have 3 parts:

  1. Initialization: Setting up the loop control variable.

  2. Condition: The expression that determines if the loop continues to execute.

  3. Update: The modification of the loop control variable after each iteration.

For loops

for <temp variable> in <collection>:
	<action>

to repeat an action

for <temp variable> in range(i):
	<action(collection)>

While loops

while <conditional statement>:
	<action>

Break

for <temp variable> in <collections>:
	<action>
	if <temp variable> == <element>
		break

Continue

for <temp variable> in <collections>:
	if <temp variable> == <element>
		continue
	<action>
	

Nested loops

for <temp variable> in <collection>:
	for <temp variable2> in <temp variable>:
		<action>

List comprehensions are a concise way to create lists by iterating over an iterable and applying an expression to each element, effectively combining the functionality of loops with the power of returning a new list.

numbers = [1, 2, 3, 4, 5]
doubled = []

for number in numbers:
	doubled.append(number * 2)

print(doubled)

#can be rewritten as:

numbers = [1, 2, 3, 4, 5]
doubled = [number * 2 for number in numbers]
print(doubled)

# we can include an if statement to change the output to <doubles> - this would print only the numbers that end up even 

numbers = [1, 2, 3, 4, 5]
doubled = [number * 2 for number in numbers if number % 2 == 0]
print(doubled)

#if we add an else condition, the if and the else have to come before the for