# if statements¶

If statements are used to control the conditions under which instructions are executed.

The general form of an if statement is:

if <<expression1>>:
body1
[elif <<expression2>>:      0 or more clauses
body2]
[else:                      0 or 1 clause
bodyN]

Let's consider this problem:

Define a function weather_report that has one parameter representing the temperature in degrees Celsius (a float) and returns a string, one of: 'Below freezing', 'Above freezing', or 'At freezing'.

Following the Function Design Recipe, we begin with Step 1, writing example calls on our function:

>>> weather_report(10)
'Above freezing'
>>> weather_report(-30)
'Below freezing'
>>> weather_report(0)
'At freezing'

Step 2 is the type contract:

(number) -> str

In [1]:
def weather_report(temp):
""" (number) -> str
>>> weather_report(10)
'Above freezing'
>>> weather_report(-30)
'Below freezing'
>>> weather_report(0)
'At freezing'
"""


In Step 4, we write an English description:

In [2]:
def weather_report(temp):
""" (number) -> str

Return one of three strings, 'Above freezing', 'Below breezing', or 'At freezing', depending on
whether temp is below 0, above 0, or equal to 0.

>>> weather_report(10)
'Above freezing'
>>> weather_report(-30)
'Below freezing'
>>> weather_report(0)
'At freezing'
"""


In Step 5, we write the body of the function, using if statments for the first time:

In [3]:
def weather_report(temp):
""" (number) -> str

Return one of three strings, 'Above freezing', 'Below breezing', or 'At freezing', depending on
whether temp is below 0, above 0, or equal to 0.

>>> weather_report(10)
'Above freezing'
>>> weather_report(-30)
'Below freezing'
>>> weather_report(0)
'At freezing'
"""

if temp > 0:
return 'Above freezing'
elif temp < 0:
return 'Below freezing'
else:
return 'At freezing'


And then we can call on the function to test it for Step 6:

In [4]:
weather_report(10)

Out[4]:
'Above freezing'
In [5]:
weather_report(-30)

Out[5]:
'Below freezing'
In [6]:
weather_report(0)

Out[6]:
'At freezing'

## Using the Python Visualizer to trace code.¶

Let's use the Python Visualizer to take a closer look how the if statement in function weather_report is executed.

## Practice Exercise: my absolute value function¶

We've used Python's built-in function abs. Now, define your own version of that function, my_abs, to calculate the absolute value of a number. Steps 1-4 of the Function Design Recipe have been completed. Completed the function body and test the function:

In [7]:
def my_abs(num):
""" (number) -> number

Return the absolute value of num.

>>> my_abs(14.66)
14.66
>>> my_abs(-2.4)
2.4
"""


## Practice Exercise: fever classification¶

According to Wikipedia, Harrison's textbook internal medicine defines a fever as a morning oral temperature greater than 37.2°C or an afternoon oral temperature greater than 37.7°C. For this problem, using the 24 hour clock, 0 to 11 hours is considered morning and 12-23 hours is considered afternoon. The first four steps of the Function Design Recipe have already been completed. Complete the function body and test the function:

In [15]:
def check_fever(temp, hour_of_day):
""" (number, int) -> str

Return 'fever' if the temperature temp in degrees Celsius recorded at hour_of_day
using the 24 hour clock meets Harrison's definition of a fever, and 'no fever' otherwise.

>>> check_fever(37.5, 9)
'fever'
>>> check_fever(37.5, 14)
'no fever'
"""


## Nested if statements¶

We also nest one if statement inside the body of another.

In [10]:
grade = 85

print('Pass')
else:
print('Fail')

Pass


Now, let's modify the program to an additional message if and only if the grade is an A:

In [11]:
grade = 85

print('Pass')
print('You earned an A!')
else:
print('Fail')

Pass
You earned an A!


## Example program: Guessing Game¶

Let's write a program that allows the user to guess a random number.

In [ ]:
secret = 4  # We can edit this to be different numbers.
guess = int(input('Enter a number between 1 and 10: '))
if guess == secret:
print('You got it')
else:
print('Better luck next time.')


## Practice Exercise: Improved Guessing Game¶

1. Write an improved version of the program above that will print either Too high or Too low depending on the guess, instead of Better luck next time.

2. Write an improved version of the program above that will print either Too high or Too low depending on the guess, in addition to Better luck next time.

## Practice Exercise: More complex if Statements¶

According to Wikipedia, borderline QTc for men is 431ms-450ms and for women it is 451ms-470ms. Set the variable sex to 'male' or 'female'), and write a program that uses the variables HR (heartrate), QT (uncorrected QT interval), and sex('male' or 'female') to print one of the strings 'normal QTc', 'borderline QTc', or 'abnormal QTc'. Here is some starter code:

In [17]:
hr = 80
qt = 300
sex = "male"
rr = 60 / hr

# Compute the corrected QT interval (QTc)
qtc = qt / (rr ** (1 / 3))

# Add code to print the appropriate message about the pateint's QTc.


## Practice Exercise: An interactive system for telling the user if their QTc is abnormal¶

Write a program that asks the user for their sex, QT interval, and heartrate, and outputs whether their QTc is normal/borderline/abnormal.

In [ ]:
# Rather than "hard code" the values assigned to hr, qt, and sex, prompt the user
# to enter values:
hr = # TODO: add code here
qt = # TODO: add code here
sex = # TODO: add code here
rr = 60 / hr

qtc = qt / (rr ** (1 / 3))   #Compute the corrected QT interval

# TODO: Add your if statement code from the previous practice exercise here.


## No if required¶

Now that you have learned how to write an if statement, it may be tempting to use it whenever possible. However, there are times when if statments aren't needed and the code is clearer and more concise with it.

Let's consider this problem: define a function is_pass that returns True if and only the given grade is at least 50.

Here is the first attempt at defining the function:

In [18]:
def is_pass(grade):
""" (number) -> bool

Return True if and only if grade is at least 50.

>>> is_pass(90)
True
>>> is_pass(15)
False
"""

return True
else:
return False


We can rewrite the function body above to use a simple Boolean expression, rather than an if statement:

In [19]:
def is_pass(grade):
""" (number) -> bool

Return True if and only if grade is at least 50.

>>> is_pass(90)
True
>>> is_pass(15)
False
"""



## Practice Exercise: rewrite without if¶

Rewrite the body of the following function, without using if statements:

In [ ]:
def is_teenager(age):
""" (int) -> bool

Return True iff age represents a teenager between 13 and 18 inclusive.

>>> is_teenager(4)
False
>>> is_teenager(16)
True
>>> is_teenager(19)
False
"""
if age < 13:
return False
else:
if age > 18:
return False
else:
return True