If Statements#
Author: Mike Wood
Learning objectives: By the end of this notebook, you should be able to:
Write an
ifstatement to control decisions within a code blockUse an
elsestatement to provife an alternative toifstatementsImplement
elifstatement to provide alternatives to a singleifstatement
if-elif-else statements#
An if statement is a handy piece of code to control whether a given piece of code is going to run. The if keyword is followed by a condition that can be interpreted to be True or False, followed by a colon. Below the if statement, all lines to be run when the condition is true are indented using 4 spaces. To end the code block, the indendation is decreased
# write an if statement that will print a statement when a condition is true
hour = 11
if hour<12:
print('It is morning')
It is morning
Often, we’d like to provide an alternative piece of code if our condition is not met – this is accomplished with an else statement. The else keyword is followed by a colon and, similar to the if block, the code to be run is indented by 4 spaces.
# write an if statement that will print a statement when a condition is true
# provide an else statement that will run when a statement is false
hour = 15
if hour<12:
print('It is morning')
else:
print('It is not morning')
It is not morning
Similarly, we may want to provide a cascade of options between the first if statement and the final else statement. In Python, the syntax for these intermediate statements is elif.
# write an if statement that will print a statement when a condition is true
# provide an altertantive elif statment if there first statement is not true
# provide an else statement that will run when none of the statements are true
hour = 9
if hour<12:
print('It is morning')
elif hour>18:
print('It is night')
else:
print('It is afternoon')
It is morning
🤔 Mini-Exercise#
Goal: Write a code block that will provide the name of the day of the week when provided with a number 1-7. For example, when week_day = 1, the block should return Monday, week_day = 5, the block should return Friday, etc. If the number is not in the range 1-7, print a statement that indicates the number is invalid.
💡 Solution#
# define the week day number
week_day = 1
# write if, elif, and else statements to print the name of the
# day of the week as described in the markdown cell above
if week_day == 1:
print('Monday')
elif week_day == 2:
print('Tuesday')
elif week_day == 3:
print('Wednesday')
elif week_day == 4:
print('Thursday')
elif week_day == 5:
print('Friday')
elif week_day == 6:
print('Saturday')
elif week_day == 7:
print('Sunday')
else:
print(week_day, 'is an invalid day number')
Monday