The if
statement allows you to specify what to do if a condition is true. Let's say you also want to specify what to do if it is not true:
vessel = "ROCINANTE"
if vessel == "QUIXOTE":
print('Vessel is named QUIXOTE')
else:
print('Vessel is named something else')
Vessel is named something else
Multiple conditions can be checked for using elif
and else
. These must immediately follow an if
statement. elif
will run the indented code if the previous condition is not true, but some other specified condition is true. else
will always run if the previous condition is not true.
vessel = "DON"
if vessel == "QUIXOTE":
print('Vessel is named QUIXOTE')
elif vessel == "ROCINANTE":
print('Vessel is named ROCINANTE')
elif vessel == "DON":
print('Vessel is named DON')
else:
print('Vessel is named something else')
Vessel is named DON
In this example, the first check is if the vessel name is 'QUIXOTE'. As it is not, a second check is done to see if the name is 'ROCINANTE'. This is true, so no further check is done.
A loop is used to run a chunk of code multiple times. The number of times may be specified in advance, or it may depend on some condition being true, such as in this example of a while
loop:
my_num = 0
while my_num < 5:
my_num = my_num + 1
print('my_num =',my_num)
print('done')
my_num = 1 my_num = 2 my_num = 3 my_num = 4 my_num = 5 done
my_num = 1
my_sum = 0
while my_num <= 10:
my_sum = my_sum + my_num
my_num += 1
print(my_sum)
55
Here the indented code will run over and over, until the condition that my_num
is less than 5 is no longer true. Because the indented code adds 1 to my_num
each time, the code block only runs 5 times. Be careful: if you'd forgotten to change the value of my_num
within the indented code block, the loop would keep on running until you force it to stop!
A for
loop is a type of loop which iterates over a number of items. For loops are often paired with range
to iterate over successive numbers:
for x in range(3):
print(x)
0 1 2
The usefulness of for
loops will become more clear in the next video.
Use a for
loop to print the sum of all numbers up to and including 100. You should get 5050.