Python Guide #8: Loops
Loops allow you to execute code within a loop multiple times, based on set conditions. There are two types of loops in python: for
and while
.
For loop
For loop lets you repeat instruction given number of times, based on some parameter. They are useful to go over indexes of a variable, or to execute program given number of times.
print("loop 1:")
# Loop below will go from i=0
# to i=9 incrementing by 1
for i in range(10):
print(i)
print("loop 1:")
# Loop below will go from i=0
# to i=8, incrementing by 2
for i in range(0, 10, 2):
print(i)
print("loop 2:")
# Loop below will go from i=1
# to i=9 incrementing by 1
for i in range(1, 10):
print(i)
print("loop 4:")
# Loop below willgo from i=10
# to i=1 decrementing by 1
for i in range(10, 0, -1):
print(i)
Execute program above and see what will happen. Modify values in ranges and see what changes.
For loop can also be executed for each element in the variable, that can be iterated over, like list
or a string
sentence = "This is a sample sentence."
l = ["element_1", "element_2", "element_3"]
# printing letter by letter
for letter in sentence:
print(letter)
# printing elements from list one by one
for element in l:
print(elements)
Execute program above and see what happens
While
While loop executes as long as the condition for the loop repeating is True
.
while condition:
# code executes
Example
counter = 0
while counter <= 10:
print(counter)
counter += 1
Execute program above and see what happens.
What next?
You have very basics of the Python already. Play around with what you have learned so far. Experiment with comparing different variables and see what changes.