While and For Loops
# loop until reaching a numeric threshold
>>> i = 0
>>> while i <= 3:
... print(i)
... i = i + 1
0
1
2
3
# loop until an empty string is returned
>>> x = "Indiana Jones"
>>> while x != "":
... print(x)
... x = x[1:]
...
Indiana Jones
ndiana Jones
diana Jones
iana Jones
ana Jones
na Jones
a Jones
Jones
Jones
ones
nes
es
s# print the result of a mathematical operation carried out over a list of items
>>> for item in [0, -99, 13, 6.54]:
... print(item ** 0.5)
0.0
(6.092540900222253e-16+9.9498743710662j)
3.605551275463989
2.5573423705088842
# run a mathematical operation on a list of items and append the outcome
# to a second list
>>> input = [2, 8, 1]
>>> output = []
>>> for item in input:
... output.append(item + 1)
>>> print(output)
[3, 9, 2]# the dictionary
>>> D = {"Thor": "Asgardian", "Vision": "android", "Wanda Maximoff": "human"}
# get the keys of D
>>> keys = D.keys()
>>> print(keys)
dict_keys(['Thor', 'Vision', 'Wanda Maximoff'])
# iterate over the keys to fetch the dictionary values and do something
# with them
>>> for k in keys:
... print(k + " IS " + D[k])
Thor IS Asgardian
Vision IS android
Wanda Maximoff IS human# the dictionary
>>> D = {"Thor": "Asgardian", "Vision": "android", "Wanda Maximoff": "human"}
# get the items of D
>>> items = D.items()
# iterate over key-value pairs and do something with them
>>> for k, v in items:
... print(k + " IS " + v)
Thor IS Asgardian
Vision IS android
Wanda Maximoff IS human# show the outcome of range
>>> list(range(3))
[0, 1, 2]
# use range in a for loop
>>> for i in range(3):
... print(i, ":-)")
0 :-)
1 :-)
2 :-)# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]
# create all permutations of letters and colors and print them
>>> for i in LETTERS:
... for j in COLORS:
... print(i, " <-> ", j)
x <-> blue
x <-> green
x <-> red
y <-> blue
y <-> green
y <-> red
z <-> blue
z <-> green
z <-> red# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]
# create one-to-one matches of items and do something with them
>>> for i, j in zip(LETTERS, COLORS):
... print(i, " <-> ", j)
x <-> blue
y <-> green
z <-> red