4.1 Boolean values
int
results in implicit type conversion. The type conversion can cause issues later in the code if the programmer assumes is_dessert
is still a Boolean.
True
is converted to
1
, and
False
is converted to
0
.
"c"
and
"c"
are equal, so
"i"
is compared to
"o"
.
"i"
is not equal to
"o"
so
False
is produced, though cilantro and coriander come from the same plant.
"d"
is greater than, not less than,
"c"
, so
False
is produced.
4.2 If-else statements
-10 < 0
is true, so num
is assigned with
25
. Then 25 < 100
, so num
is assigned with 25 + 50
, which is
75
.
positive_num
is always assigned with
0
. The positive input value is lost.
if
branch is taken when x >= 15
, so the
else
branch is taken when x
is not greater than or equal to
15
.
if-else
statement. Depending on x'
s value, y
will either have a final value of
30
or
105
.
4.3 Boolean operations
3000 > 3000
is
False
. False and True is
False
. False and False
is
False
. So no value of hrs_to_close
will allow Darcy to enter.
(8 < 10) and (21 > 20)
evaluates to True and True
, which is
True
. So the body of the
if
is executed, and z
is assigned with
5
.
(9%2==0 and 10%2 ==1)
evaluates to (False and False)
, which is
False
. (9%2 == 1 and 10%2 == 0)
evaluates to (True and True)
, which is
True
. False or True
is
True
. The
if
statement checks whether the numbers form an even-odd or odd-even pair.
not(18 > 15 and 18 < 20)
evaluates to not(True and True)
, then not(True)
, and finally,
False
.
4.4 Operator precedence
4.5 Chained decisions
elif
will evaluate condition_2
if condition_1
is
False
and execute Body 2
if condition_2
is
True
.
x > 44
, 42 > 44
, is
False
, so x < 50
is evaluated. 42 < 50
is
True
, so y = 0 + 5
. Only one of the
if
and
elif
branches is taken.
if
and if-elif
statements are not chained. The first
if
evaluates to
True
and executes. Then the if-elif
is evaluated and the
elif
branch executes.
-1 < 0 and -2 < 0
is
True
, so y = 10
.
price < 9.99
. The second branch executes if price < 19.99
and the first condition fails: that is, price >= 9.99
. The third branch executes if the first and second conditions fail: that is, price >= 19.99
. Chaining can simplify decision statements.
4.6 Nested decisions
num_dancers
is positive, so the
else
branch is taken. num_dancers
is odd, so the error is printed before the program continues after the nested
if
and prints num_dancers
.
256 == 513
is
False
, and 256 < 513
is
True
, so the
elif
branch is taken and Body 2
executes. 513 >= 512
is
True
, so Body 3
executes.
else
isn't indented and is treated as the
else
to the original
if
. Thus the second
else
is not connected to an
if
statement and produces an error.
4.7 Conditional expressions
response
with
"even"
if x
is even. response
is assigned with
"odd"
if x
is odd.
min_num
cannot be assigned with min_num = y
. The correct expression is min_num = x if x < y else y
"
(fee + 10) if hours > 12 else 2
. So if hours > 12, the result will be fee + 10; otherwise, the result will be 2.