For Loops.¶

In [1]:
# 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
In [2]:
# Let us print some numbers on the screen
for i in range(0,4):
    print(i)
0
1
2
3
In [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
In [4]:
a = ['apple', 'banana', 'orange']
In [5]:
# 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]
In [6]:
type(a[5])
Out[6]:
int

Practice! Create a list of 5 elements (of different types) and write a for loop that prints only the integers of that list.

In [7]:
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.¶

In [8]:
# 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
In [9]:
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!