Using Python for basic computations.
Expressions
We can use Python as a fancy calculator to help us with basic computations. For example, 2 + 3 will evaluate to 5 as expected. The SageCell below is a place where you can practice evaluating lines of Python code. Use this cell to evaluate several mathematical expressions using the arithmetic operators mentioned before. Note that SageCells run a special form of Python with additional features. This means that there are cases where the output of the SageCell will be different from what regular Python (Python3) produces. In general this will not be a problem.
Comparisons
Comparisons return either a True or False value depeding on whether or not the given statement holds. For example, 3 < 1 would evaluate to False. Comparisons will allow us to write code that reacts to different inputs. Use the cell below to evaluate several comparisons. Note that in Python, == is how you check whether or not two quantities are equal while = is reserved for assignment.
Data Types
We will be working with different data types, like integers, strings, and lists. Each one comes equipped with functions and operators whose output depends on the data types that they act on. More on data types will be covered as needed in later sections. We will make use of the following data types:
- int - integers like 0, 3, or -5.
- float - numbers with fractional parts like 2.5
- bool - boolean values (True or False)
- char - a single character enclosed in single or double quotes, like "c" or "3" (note that the integer 3 is different from the character "3")
- string - a collection of characters, like "hello"
- lists and arrays (to be covered later)
And/Or
If you need to check multiple conditions using the logical connectives “and” or “or”, simply use the Python keywords and and or. In the case of A and B, the statement will be true if A and B are both true, and false otherwise. In the case of A or B, the statement will be false if A and B are both false, and true otherwise.
For example, 3 > 4 and 4 > 5 is false, but 3 > 4 or 4 > 5 is true. (Note the order of operations here as we do not need parentheses around the comparisons.)
Boolean Values
The boolean values True and False can be used in a few ways. They are the outputs of a Python expression like the comparisons seen above. Later we will see that they can be used as the output of a function to decide what a program does next (see the decision compartments in the Flowcharts section).
A SageCell
Write your Python code in the cell below and click on the ‘Evaluate’ button below to see the result.