How to use a for
loop? in Python#
The for
loop has 2 main components:
an iterating variable e.g.
i
a list of desired values e.g.
range(3)
will be three valuesi = 0, i = 1, i = 2
These loops are great when you want to repeat the same command multiple times. You can use the variable to update your command.
Consider this for
loop, the iterating variable is i
and the desired values are range(3)
:
for i in range(3):
print('i =', i)
i = 0
i = 1
i = 2
The for
loop reassigns a variable e.g. i
each time it finishes the commands that are tabbed.
for <variable> in <desired_values
\(\rightarrow\) <run these commands>
You can accomplish the same output without a for
-loop by copy-pasting the print
command:
print('i = ', 0)
print('i = ', 1)
print('i = ', 2)
i = 0
i = 1
i = 2
Use a for
loop to calculate a sum#
The np.sum
will sum the values of an array, but if you have a Python list inside [
and ]
it will return an error. You can use a for
loop to calculate this value (if possible use NumPy though!). Here is the process:
define the vector,
v
initialize the value for your sum,
sum_v
create a
for
-loop that assigns your variable to each value ofv
,for vi in v:
inside the
for
-loop, add each value tosum_v
,sum_v += vi
v = [1, 2, 3, 10]
sum_v = 0
for vi in v:
sum_v += vi
print('sum of vectors components in v is', sum_v)
sum of vectors components in v is 16
Wrapping up#
In this notebook, you built some for
-loops to print
and add variables from desired values. You can use the for
loops to repeat the same command multiple times while changing the the iterating variable.