Looping
Backwards
> for i in reversed(range(5)):
print(i)
...
4
3
2
1
0
List Backwards
> my_list = ['a', 'b', 'c', 'd', 'e']
> for i in reversed(range(0, len(my_list))):
print(my_list[i])
...
e
d
c
b
a
Basic Loop
> my_list = ['a', 'b', 'c', 'd', 'e']
> for x in range(len(my_list)):
print(x)
...
0
1
2
3
4
Enumerate
> my_list = ['a', 'b', 'c', 'd', 'e']
> for count, value in enumerate(my_list):
> print(count, value)
...
0 a
1 b
2 c
3 d
4 e
Front / Back Same Time
> my_list = ['a', 'b', 'c', 'd', 'e']
> for i in range(len(my_list) // 2):
> print(my_list[i], my_list[~i])
...
a e
b d
# NOTE: It does not reach the middle element for an odd length
While/For Else
counter = 0
while counter <= 5:
print counter,
counter += 1
else:
print "loop exited normally"
# Output: 0 1 2 3 4 5 loop exited normally
for i in range(5):
print i,
if i > 3:
break
else:
print "loop exited normally"
# Output: 0 1 2 3 4
Continue
Continues the next iteration of the loop
> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Pass
It does nothing, can be used when a statement requires an action
> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Break
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')