2 < 3
True
Here’s a question: is 2
less than 3
? Well, yes it is! If we wanted to confirm this, we could simply ask Python whether 2
is less than 3
by running
2 < 3
True
Notice, however, how Python answered this question: it simply returned True
. Let’s see what the data type of True
is:
type(True)
bool
True
is of the type bool
, which is short for boolean
. There are only two boolean quantities in Python: True
and False
. Let’s see how we can generate a False
value:
3 < 2
False
Here is a list of comparison operators, taken from the Inferential Thinking textbook:
Comparison | Operator | True Example | False Example |
---|---|---|---|
Less than | < |
2 < 3 |
2 < 2 |
Greater than | > |
3 < 2 |
3 > 3 |
Less than or equal | <= |
2 <= 2 |
3 <= 2 |
Greater than or equal | >= |
3 >= 3 |
2 >= 3 |
Equal | == |
3 == 3 |
3 == 2 |
Not equal | != |
3 != 2 |
2 != 2 |
One nice thing about Python is that it allows for multiple simultaneous comparisons. For example,
2 < 3 < 4
True
In a multiple comparison, Python will only return True
when all of the included comparisons are true.
For instance, 2 < 3 < 1
would return False
, because even though 2
is less than 3
it is not true that 3
is less than 1
.
Believe it or not, you can compare strings as well! Python compares strings alphabetically; that is, letters at the beginning of the alphabet are considered to have smaller ordinal value than letters at the end of the alphabet. For example:
"apple" < "banana"
True
"zebra" < "zanzibar"
False
"cat" <= "catenary"
True
Check how "statistics"
and "Statistics"
(note the capitalization!) compare. Use this to answer the question: when Python is comparing strings, does it give precedence to capital letters or not?
Finally, we discuss how comparisons work in the context of lists and arrays. The way Python compares lists is by what is known as lexicographical order. From the official Python help documentation, this means
first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
For instance, [1, 2, 3] < [2, 1, 1]
would return True
since 1
(the first element of the first list) is less than 2
(the first element of the second list).
The comparison of arrays is a little more straightforward, except
When comparing two arrays, the arrays must be of the same length.
To see exactly how comparison of arrays works, let’s work through a Task:
Make an array with the elements 1
, 2
, and 3
, and call this x
. Make another array with the elements 2
, 3
, 1
, and call this y
. Run x < y
, and comment on the result.
What the previous task illustrates is that Python compares arrays element-wise.
Now, we can use comparisons for much more than verifying simple arithmetic relationships. One of the main areas in which comparisons arise is the area of conditional expressions.
Simply put, conditional expressions are how we can convey a set of choices to Python. As an example, let’s consider finding someone’s city based on their zip code. To simplify, let’s assume the only zip codes we consider are 9311
, 93120
, and 93150
. From postal data, we know that:
93117
corresponds to Goleta93120
corresponds to Santa Barbara93150
corresponds to MontecitoWe can rephrase this information in terms of “if” statements:
93117
, then they are in Goleta93120
, then they are in Santa Barbara93150
, then they are in MontecitoThis is precisely the syntax we would use when translating this experiment into Python syntax:
if zip_code == 93117:
= "Goleta"
location elif zip_code == 93120:
= "Santa Barbara"
location elif zip_code == 93150:
= "Montecito" location
By the way: elif
is an abbreviation for else if
, which itself can be thought of as equivalent to otherwise, if
.
Here’s the general syntax of a conditional expression in Python:
if <condition 1>:
<task 1>
elif <condition 2>:
<task 2>
...else:
<final task>
When executing the above conditional statement, Python first checks whether <condition 1>
returns a value of True
or False
. If it returns a value of True
, then <task 1>
is executed and the statement ends. Otherwise, Python checks whether <task 2>
is True
or False
; if it is True
then <condition 2>
is executed, etc.
In the example code above: if <condition 1>
is True
, then no tasks beyond <task 1>
are evaluated. If <condition 2>
is True
, then no tasks beyond <task 2>
are evaluated. And so on and so forth.
Consider the code:
= 2
x
if x < 2:
= "hello"
x elif x < 3:
= "goodbye"
x else:
= "take care" x
Before running any code, write down what you think the result of executing x
would be. Then, run the loop, execute x
, and check whether your answer was correct or not.
Indentation is very important in Python.
For example, if instead of the conditional expression in Task 3 we had instead put
= 2
x
if x < 2:
= "hello"
x elif x < 3:
= "goodbye"
x else:
= "take care" x
then we would have received an error!
Finally, let’s quickly discuss Python functions. We’ve already been using quite a few functions:
In a Markdown cell, write down three functions we’ve used in the previous labs.
If you recall, the general syntax for calling a function is:
<function name>(<arg1>, <arg2>, ... )
where <function name>
denotes the function name and <arg1>
, <arg2>
, etc. denote the arguments of the function.
Creating your own function in Python is actually fairly simple! Here is the syntax we use:
def <function name>(<list out the argument names>):
"""include a 'docstring' here"""
<body of the function>
return <what you want the function to output>
For example,
def f(x, y):
"""returns x^2 + y^2"""
return x**2 + y**2
creates a function f
that can be called on two arguments, x
and y
, and returns the sum of squares of the arguments; e.g.
3, 4) # should return 3^2 + 4^2 = 25 f(
25
By the way, the docstring referenced above is a verbal description of what the function does. (Recall from Lab01 that it is just a multi-line comment, since it is enclosed in triple quotation marks!). All functions should include a docstring to convey to the user what the function does.
If you don’t include a return
statement in the definition of a function, then your function will never return anything.
For instance,
def g(x, y):
"""should return x^2 + y^2"""
**2 + y**2
x
3, 4) g(
Write a function called cent_to_far()
which takes in a single temperature c
as measured in degrees Centigrade and returns the corresponding temperature in degrees Farenheit. Check that cent_to_far(0)
correctly returns 0
and cent_to_far(68)
correctly returns 69.7777
. As a reminder: \[ {}^{\circ}\mathrm{F} = \frac{5}{9} ({}^{\circ}\mathrm{C}) + 32 \]
Finally, let’s combine some things by way of a concluding Task:
Write a function called parity()
that returns the parity (i.e. whether a number is even or odd) of an input x
. Call your parity()
function on 2
and then 3
to make sure your function behaves as expected. Some hints:
%
is the modulus operator in Python. Specifically, x % y
returns the remainder of performing y
divided by x
.2
(so what does this mean about the remainder of dividing x
by 2
if x
is even?)