Python - Loops

python logo pixel art

Python uses loops to repeat a block of code until the loop condition is met.


`while`

while loop

While loop repeat until a condition is met; if the condition is never met, the loop will be infinite.

while condition:
  # tasks...
while condition:
  # tasks...
else:
  # tasks... (executed on loop end)
n = 0
while n < 10:
  n += 1
  print(n)

`for`

For loop is used to go through each item in an iterable or a range.

range

for i in range(start, end, step):
  # tasks...
for i in range(start, end, step):
  # tasks...
else:
  # tasks... (executed on loop end)
for n in range(10): 
  print(n) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  
for n in range(2, 10): 
  print(n) # 2, 3, 4, 5, 6, 7, 8, 9
  
for n in range(2, -10, -2): 
  print(n) # 2, 0, -2, -4, -6, -8

Iterable

for i in iterable:
  # tasks...
for i in iterable:
  # tasks...
else:
  # tasks... (executed on loop end)
for char in "python":
  print(char)
  
for item in [33, 41, 52, 99]:
  print(item)