Python course at https://codecademy.com
Python flow control tutorial https://docs.python.org/3/tutorial/controlflow.html
The range()
command offers an easy way to loop over a sequence of numbers. Remember that Python is 0 indexed.
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
We can also loop over anything that is iterable, this includes lists, tuples, and dictonaries.
alist = ['a', 'b', 'c']
In the loop below aletter
takes on each value of alist
every cycle through the loop.
for aletter in alist:
print(aletter)
a b c
There are also while
-loops, but the syntax is not as clear as for
-loops and there is always a danger of entering an infinite loop.
i=0
mybool = False
while mybool is not True:
print(i)
i += 1
if i > 10:
mybool = True
0 1 2 3 4 5 6 7 8 9 10
I prefer for
-loops with a fixed number of iterations and a break
statement to replicate the logic of while
-loops, but protecting from infinite cycles.
for i in range(100):
print(i)
if i > 10:
break
0 1 2 3 4 5 6 7 8 9 10 11
Here is an example of a conditional statement with and
or or
logic.
for i in range(100):
if i < 10 or i > 20:
print(i)
else:
print("Hello!")
0 1 2 3 4 5 6 7 8 9 Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
Python offers a clean syntax for testing if an item is stored in a list, tuple, or dictionary.
alist = ['a', 'b', 'c']
if 'd' not in alist:
print("True!!!!")
else:
print("False!!!!")
True!!!!