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
Now in Step 3, we add the function header:
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:
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:
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:
weather_report(10)
weather_report(-30)
weather_report(0)
Let's use the Python Visualizer to take a closer look how the if statement in function weather_report is executed.
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:
def my_abs(num):
""" (number) -> number
Return the absolute value of num.
>>> my_abs(14.66)
14.66
>>> my_abs(-2.4)
2.4
"""
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'
"""
if statements¶We also nest one if statement inside the body of another.
For example, let's consider this code that reports information about grades:
grade = 85
if grade >= 50:
print('Pass')
else:
print('Fail')
Now, let's modify the program to an additional message if and only if the grade is an A:
grade = 85
if grade >= 50:
print('Pass')
if grade >= 80:
print('You earned an A!')
else:
print('Fail')
Let's write a program that allows the user to guess a random number.
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.')
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.
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.
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:
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.
Write a program that asks the user for their sex, QT interval, and heartrate, and outputs whether their QTc is normal/borderline/abnormal.
# 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.
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:
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
"""
if grade >= 50:
return True
else:
return False
We can rewrite the function body above to use a simple Boolean expression, rather than an if statement:
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 grade >= 50
if¶Rewrite the body of the following function, without using if statements:
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