# For-loops.
# For-loops have the following structure:
#
# for i in RANGE:
# complete_action
#
# i - the counter in a for-loop and can be incorporated into
# complete_action
#
# RANGE - provides a range for the number of times complete_action is run
#
# complete_action - the code that is to be executed until i (the counter)
# reaches the maximum number of times.
#
# Let's see an example
# Let us print some numbers on the screen
for i in range(0,4):
print(i)
0 1 2 3
# What is the difference with this loop?
for i in range(4):
print(i)
print('hello')
0 hello 1 hello 2 hello 3 hello
a = ['apple', 'banana', 'orange']
# Let us write a for loop that appends a number to a list
for i in range(len(a)):
#list.append(a,i)
a.append(i)
print(a)
['apple', 'banana', 'orange', 0] ['apple', 'banana', 'orange', 0, 1] ['apple', 'banana', 'orange', 0, 1, 2]
type(a[5])
int
Practice! Create a list of 5 elements (of different types) and write a for loop that prints only the integers of that list.
b = ['donuts',3.0, 55, 22, 'chicken nuggets']
print(b[0])
print(b[1])
print(b[2])
print(b[3])
print(b[4])
donuts 3.0 55 22 chicken nuggets
# While-loops have the following structure:
#
# while EXPRESSION:
# complete_action
#
# EXPRESSION - provides a range (or a condition)
# for the number of times complete_action is run
#
# complete_action - the code that is to be executed until i (the counter)
# reaches the maximum number of times.
#
# Let's see an example
y = 1
while y < 10:
y = y + 1
#y += 1 # this increments y by 1 each time
print(y) # What value of y should be printed?
10
Practice! Modify the while loop above so that it never stops!