Control Structures

Iteration#

While Loops#

while i <= 5:
doSmth()

For Loops#

for item in [1, 2, 3, 4]:
print(item)

Looping with Index

n = len(arr)
for i in range(n):
do_smth(arr[i])

or

for idx, val in enumerate(ints):
print(idx, val)

Selection#

If-Elif-Else#

if item >= 10:
print('yes')
elif item == 5:
print('yup')
else:
print('ok')

List Comprehension with Iteration & Selection#

Normal way:

alist = []
for x in range(0, 11):
alist.append(x*x)

With list comprehension:

alist = [x*x for x in range(0, 11)]

Specify criteria:

alist = [x*x for x in range(0, 11) if x%2 == 0]
[ch.upper() for ch in 'comprehension' if ch not in 'aeiou']