Loops
Basic
Prints: 2 3 5 7
With index
animals = ["dog", "cat", "mouse"]
# enumerate() adds counter to an iterable
for i, value in enumerate(animals):
print(i, value)
Prints: 0 dog 1 cat 2 mouse
While
Prints: 0 1 2 3
Break
Prints: 0 10 20 30 40
Continue
Prints: 30 40 60 70
Range
for i in range(4):
print(i) # Prints: 0 1 2 3
for i in range(4, 8):
print(i) # Prints: 4 5 6 7
for i in range(4, 10, 2):
print(i) # Prints: 4 6 8
With zip()
words = ['Mon', 'Tue', 'Wed']
nums = [1, 2, 3]
# Use zip to pack into a tuple list
for w, n in zip(words, nums):
print('%d:%s, ' %(n, w))
Prints: 1:Mon, 2:Tue, 3:Wed,
for/else
nums = [60, 70, 30, 110, 90]
for n in nums:
if n > 100:
print("%d is bigger than 100" %n)
break
else:
print("Not found!")
Also see: Python Tips