6.1. Loops#
6.1.1. Repeating code using loops#
for <ele> in <sequence>:
<body>
The loop index variable
ele
takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value.For loops have a limitation – you have to know how many times you are looping – it is a definite loop. The number of iterations is determined when the loop starts. If you do not know how many times you will be looping, use a while loop, which is an indefinite loop that will continue to loop until its condition is no longer true.
while <condition>
<body>
6.1.2. Controlling Loops#
break
- Used to break a loopcontinue
- Used to skip the current loop and go to the next value
6.1.3. Range#
range(start,stop,step) # [start:step:stop)
6.1.4. Examples#
6.1.4.1. Example 1#
values = [4, 10, 3, 8, -6]
for i in range(len(values)):
print(i)
6.1.4.2. Example 2#
values = [4, 10, 3, 8, -6]
for i in range(len(values)):
print(i, values[i])
6.1.4.3. Example 3#
values = [4, 10, 3, 8, -6]
for i in range(len(values)):
print(i, values[i])
6.1.4.4. Example 3#
values = [4, 10, 3, 8, -6]
for index, value in enumerate(values):
print(index, value)
6.1.4.5. Example 4#
values = [4, 10, 3, 8, -6]
for i in range(len(values)):
values[i] = values[i] * 2
6.1.4.6. Example 5#
metals = ['Li', 'Na', 'K']
weights = [6.941, 22.98976928, 39.0983]
for i in range(len(metals)):
print(metals[i], weights[i])
6.1.4.7. Example 6#
metals = ['Li', 'Na', 'K']
weights = [6.941, 22.98976928, 39.0983]
for metal, weight in zip(metals, weights):
print(metal, weight)
6.1.4.8. Example 7#
elements = [['Li', 'Na', 'K'], ['F', 'Cl', 'Br']]
for inner_list in elements:
for item in inner_list:
print(item)
6.1.4.9. Example 8#
info = [
['Isaac Newton', 1643, 1727],
['Charles Darwin', 1809, 1882],
['Alan Turing', 1912, 1954, 'alan@bletchley.uk']
]
for item in info:
print(len(item))
6.1.5. How to sum numbers in an array?#
x = [1, 7, 3]
sum = 0
for ele in x:
sum = sum *10 + ele
6.1.6. How to sort without sorting?#
string1 = '1134000234'
string2 = ''.join(sorted([ele for ele in string1]))
string3 = ''.join(sorted([ele for ele in string1], reverse=True))
print(string1, string2, string3)
store = [0] * 10
for char in string1:
index = int(char)
store[index] += 1
sorted_string = ''
for idx, ele in enumerate(store):
sorted_string += str(idx) * ele
print(sorted_string)
6.1.7. How to sum an integer?#
number = 1234
sum = 0
while number:
sum += number % 10
number = number // 10
print(sum)
6.1.8. File Handling#
with open(filename, 'r') as file:
for line in file:
if not line.strip(): # used for skipping empty lines!
continue
# do something with line
6.1.9. Skipping Bad values#
You can use a try/except
blocks to skip bad values
try:
value = float(line)
except:
continue
6.1.10. Initial Values#
Sometimes before the for loop code you to have initialize a variable to 0 or an empty list.
If you want to calculate the average or sum of a list, for example, you would need to initialize a variable to zero and update it every time you access a new element in a list.
total = 0
count = 0
for value in my_list:
total += value
count += 1
average = total / count
If you want to keep track of some values as you loop over some list, you might need to initialize an empty list. One example is removing duplicates from a sequence.
unique_values = []
for ele in sequence:
if ele not in unique_values:
unique_values.append(ele)