|
CS 140: Introduction
to Computer Programming
Logical
Connectives
When checking whether or not to execute a
certain block of code (for instance when using if,
elif,
or while
statements) it is frequently desirable to check
more than one thing at once. For instance,
to find out whether a number is in the 70s, we
must both ensure that the number is more than 69
and also less than 80, which is done by
writing
number = input("Enter a two-digit number:
")
if number >
69 and number
< 80:
print
"Your number was in
the 70s"
The if
statement becomes slightly more clear if we
write
if number
>= 70 and
number <= 79:
but either version will work.
HEADS UP! The customary way
of phrasing this condition in English goes
something like "If the number is greater than or
equal to 70 and less than or equal to
79..." However, it is not
valid to write
if number
>= 70 and
<= 79:
Python will object, since it can check whether number
>= 70 but is unable to make
sense of <= 79 by
itself.
To test whether a number is not in the 50s we
must determine that it is either too small or
too large.
number = input("Enter a two-digit number:
")
if number <
50 or number
> 59:
print
"Your number was not
in the 50s"
As before, there is an equivalent formulation
using
if number
<= 49 or
number >= 60:
It is perfectly acceptable to string together
several and
or or
connectives in a row. Thus we could write
if number
== 1 or number
== 4 or number == 9:
print "Your number is a
one-digit perfect square."
We can do the same thing with and
statements, as in
if
number%2 == 0 and
number >= 10 and number <= 99:
print "Your two-digit number is
even."
It is also possible to combine both and
and or
connectives on a single line, and include
parentheses, but we won't need to worry about
such complicated constructions.
|
|
|