Download 1 The if statement

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSC120 Worksheet 2 – If Statements and the Boolean Type
1
The if statement
In everyday life, we often make decisions based on the current conditions.
If the weather is warm,
I wear shorts.
Otherwise,
I wear pants.
The same conditional process appears when writing code. To handle these situations we use an if
statement.
Example.
English
Check The Temperature:
If the temperature > 0 then
it is above the freezing point
Otherwise, if the temperature = 0 then
it is at the freezing point
Otherwise
it is below the freezing point
Form for writing an if statement:
→
→
→
→
→
→
→
→
Python
def check temp(temperature):
if temperature > 0:
return "above the freezing point."
elif temperature == 0:
return "at the freezing point."
else:
return "below the freezing point."
if condition 1:
statements 1
elif condition 2:
statements 2
else:
statements 3
The details:
- statements 1 only executes if condition 1 is true.
- statements 2 only executes if condition 2 is true and condition 1 is false.
- statements 3 only executes if condition 1 and condition 2 are false.
- there can be 0 or more elif statements,
- there can be at most one else statement.
We can also nest if statements. Fill in the Python lines below that are missing:
1
English
Check The Temperature:
If the temperature > 0 then
If the temperature > 100 then
it is above the boiling point
Otherwise, if the temperature > 37 then
it is above body temperature
Otherwise,
it is above the freezing point
Otherwise, if the temperature = 0 then
it is at the freezing point
Otherwise
it is below the freezing point
→
Python
→
→
→
→
→
→
→
→
→
→
→
→
def check temp(temperature):
if temperature > 0:
elif temperature == 0:
return "at the freezing point."
else
return "below the freezing point."
What type are the conditions in the if statements above?
2
The Boolean type
A true/false value is called a Boolean type, named after George Boole, a philosopher and logician
of the early 19th century. In Python we denote the Boolean type by bool. We have already seen
Boolean conditions such as:
temperature > 0 and temperature == 0
The only two values of type bool are True and False (with capital letters). There are many
operators in Python that evaluate to True or False. Some are conditional operators, while
others are logical operators.
For each of the following expressions that use conditional operators, write down the result that
they evaluate to:
3 < 4
3 > 8
8 > 3
3.5 >= 3.5
7 == 7
x == 7
y == 7.0
x == y
3 != 4
# Why not just one equals sign?
Suppose that snowing and sunny are of type bool. They can refer to a value of either True or False.
snowing = False
sunny = True
2
For each of the following expressions involving logical operators, write down the value of the expression. A logical operator is one that takes either one or two booleans and returns a boolean.
The most common ones are not, or and and.
and evaluates to True if and only if both operands are True.
or evaluates to True if at least one operand is True.
not evaluates to True if its one operand is False, and True otherwise.
not snowing
# "not" is a unary operator: 1 operand
not sunny
sunny and snowing
# "and" and "or" are binary operators:
sunny or snowing
a = False
# assign a the value False
b = True
# assign b the value True
not a or b
# precedence?
(not a) or b
not (a or b)
not not a
# double negative
not not not a
2 operands
We can also combine many conditionals using logical operators, for example:
x < 0 or x > 100
Let a, b, c, d be boolean variables assigned the following values:
a = True
b = True
c = False
d = False
Determine the value of each of the following expressions:
not (a and c)
not a or not c
(a or d) and not (c or b)
not (not a or not c)
2.1
Boolean representation
False is stored internally as 0 and True as 1. In fact, Python treats any numeric value not equal
to 0 as True. This means that:
False < True and
if 10.5:
print "10.5 is true!"
prints 10.5 is true!
3
Q. What does this little program print?
num = 6
if num == 10 or 20 or 30:
print("yay")
else:
print("no way")
A. “yay”
2.2
Lazy evaluation
Python is “lazy” when it evaluates boolean expressions.
if x and y:
...
If x is False, Python doesn’t bother to evaluate y.
Q. What value of x would force Python to evaluate y in (x or y)?
A.
Lazy evaluation allows us to simplify our code. For example:
Suppose you write a program that reads in some temperature data. It has just read all
the data recorded for January 16. Variable sum has the total of those values, and n has
the number of values that were read. If the average temperature reading that day was
above freezing, you want to print a message saying so.
if sum / n > 0:
print "Average was above freezing."
Q. What problem may occur?
A.
Q. How can we fix this?
A.
4
2.3
Boolean good practice
• Use parentheses to indicate precedence. This reassures your readers, who can’t remember
the precedence rules, and avoids the errors you will make because you can’t remember the
precedence rules.
• Use the simplest expression possible. Some examples:
Avoid double negatives such as “not not a”; “a” is much clearer.
Avoid explicit comparison to True or False:
# Suppose you have a boolean variable below_zero.
if below_zero == True:
print "Brrrr!"
# That is like saying:
if (temperature < 0) == True:
print "Brrr!"
# Obviously silly, but equivalent
Q. Is there a simpler way to write the first if statement?
A.
Q. Can you simplify this function?
def is_odd(x):
if x % 2 == 1:
return True
else:
return False
A.
5