Conditionals¶
Use if
statements to control whether or not a block of code is executed.¶
An
if
statement (more properly called a conditional statement) controls whether some block of code is executed or not.Structure is similar to a
for
statement:First line opens with
if
and ends with a colonBody containing one or more statements is indented (usually by 4 spaces)
masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 3.0:
print(m, 'is large')
else:
print(m, 'is small')
Conditionals are often used inside loops.¶
Not much point using a conditional when we know the value (as above).
But useful when we have a collection to process.
Use else
to execute a block of code when an if
condition is not true.¶
else
can be used following anif
.Allows us to specify an alternative to execute when the
if
branch isn’t taken.
Use elif
to specify additional tests.¶
May want to provide several alternative choices, each with its own test.
Use
elif
(short for “else if”) and a condition to specify these.Always associated with an
if
.Must come before the
else
(which is the “catch all”).
masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 9.0:
print(m, 'is HUGE')
elif m > 3.0:
print(m, 'is large')
else:
print(m, 'is small')
Conditions are tested once, in order.¶
Python steps through the branches of the conditional in order, testing each in turn.
So ordering matters.
grade = 85
if grade >= 70:
print('grade is C')
elif grade >= 80:
print('grade is B')
elif grade >= 90:
print('grade is A')
Often use conditionals in a loop to “evolve” the values of variables.
velocity = 10.0
for i in range(5): # execute the loop 5 times
print(i, ':', velocity)
if velocity > 20.0:
print('moving too fast')
velocity = velocity - 5.0
else:
print('moving too slow')
velocity = velocity + 10.0
print('final velocity:', velocity)
masses = [3.54, 2.07, 9.22, 1.86, 1.71]
def get_values(min,max):
'''
Gets the values inside an array in a given range
'''
for m in masses:
# Here we can use multiple conditions to execute the code block
if (m >= min and m <= max and m > 3.0):
print(m, 'is large')
elif(m >= min and m <= max):
print(m, 'is small')
get_values(1,6)