Loops

for Loops

Many programming languages support 'numeric' for loops, which work based on a range of conditions— usually whether or not a number is less than or greater to another value— and each run through the loop, test that value to see whether or not the loop should continue.

Python, on the other hand, only has 'generic' for loops, in which each run-through of the loop sees the loop iterating through a sequence of some sort.

for i in range(10):
	print(i)

The above will print numbers from 0 to 9.

Keep in mind that range() is partially non-inclusive— which is to say that list(range(2, 6)) actually generates a list of [2, 3, 4, 5] when called, excluding the final digit.

Iterating through a string:

for ch in "string":
	print(ch.upper(), end=" ")
S T R I N G

Iterating through a list:

items = ["food", "water", "shelter", "garbage"]

for obj in items;
	if len(obj) > 6:
		print(obj)

The above will print any items which have more than 6 characters, which happens to be "shelter" and "garbage".

It is also possible to iterate over multiple sequences at the same time, as well as to iterate over sequences within sequences.

list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]

for num1, num2, in zip(list1, list2):
	print(num1 + num2)

zip(list1, list2) will transform list1 and list2 as a list of tuples, with each pair of values being their own tuple: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]. This allows for taking each value while iterating through each tuple.

while Loops

Python also features while loooping, which works as it does in other languages.

x = 0
while x < 10:
	print(x)
	x += 1

This is equivalent to the for loop featured earlier; it will print numbers from 1 to 9.

stuff = ""
num = 65

while 'Z' not in stuff:
	stuff +=  chr(num)
	num += 1

print(stuff)

This will print every ASCII character from A-Z:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Choosing Syntax

Which looping construct should you use? In the end, it is entirely up to you; however, you may find that some situations will be easier to handle using one or the other.

Avoiding Unnecessary Looping

There are some cases where a loop may seem like a good idea:

a = [1, 3, 5, 7]
for num in a:
	if num == 5:
		print(num)

When in reality, Python contains other features which make performing the same task easier— making looping either redundant or an inferior method to perform the task.

a = [1, 3, 5, 7]
if 5 in a:
	print(5)