This topic can be challenging, however, we already know the basics. Let's work together and get ready for Assignment 1.
By the end of this notebook you will be able to:
for
loops are normally used for.Before we start: One of the essential data structures in Python is a List, which is a data type that stores many values in a single variable. For instance:
temperature = [0.234, 0.434, 0.55, 0.423]
print(temperature)
[0.234, 0.434, 0.55, 0.423]
In the next tutorial we'll learn more about List data type.
## Let's create a List with my students
my_students = ["Alice", "Xiaojing", "Julio", "Victoria", "Maria", "Turgay"]
print(my_students)
['Alice', 'Xiaojing', 'Julio', 'Victoria', 'Maria', 'Turgay']
## Let's say I'm teaching a tutorial, and I want to save the names of all of my students
## One way is to create a variable for each one, and save one name per variable
student_1 = "Alice"
student_2 = "Xiaojing"
student_3 = "Julio"
## This works ok... but it makes more sense to keep a single list!
my_students = ["Alice", "Xiaojing", "Julio", "Victoria", "Maria", "Turgay"]
print(my_students)
['Alice', 'Xiaojing', 'Julio', 'Victoria', 'Maria', 'Turgay']
Elements within a list can be accessed by their index number
Index numbers start at index 0, meaning that the first element in the list is at element 0
my_students[0] ## You access elements of a list using this notation
my_students[1]
'Xiaojing'
So, a for loop is one of the most fundamental operations to learn properly how to code and automate things, but can be tricky to learn for the first time. Python has several ways of performing loops.
# for each element in the list, do these operations
for number in [1,2,3,4]:
print(number)
1 2 3 4
[1,3,5]
, is what the loop is being run on.print(number)
, specifies what to do for each element in the list.number
, is what changes for each iteration of the loop (i.e., the current element).The first line of the for loop must end with a colon :
, and the body must be indented:
{}
or begin/end
to show nesting:range
to iterate over a sequence of numbers:¶range
produces a sequence of numbers.range(N)
is the numbers 0 ... N-1.## We use a function to automatically create a list of numbers, starting at 0,
## and ending at 19
my_numbers = list(range(0,20))
my_numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
EXERCISES - 5 min
list
with member states of the Association of SouthEast Asian Nations.for instance:
ASEAN_countries = ["", "", "", ""]
list
with the ASEAN memebers statesmy_numbers = list(range(0,20))
for number in my_numbers:
if number == 5:
print("Hey, I love 5!")
else:
print(number)
brics = ['Brazil', 'Russia', 'China', 'South Africa']
print('the least populated country within BRICS is', brics[4])
my_students = []
for ___ in my_students:
print()