= 6 / 3
x print(x)
= 5 / 3
y print(y)
= 1 + 2.5
z print(z)
2.0
1.6666666666666667
3.5
By the end of this module, for simple “Hello World”-like programs, you will be able to:
for
loops.for
loops and calculations.Python uses variables, similar to variables in algebra, to store information. Consider the analogy of variables as storage boxes. Consider the following rules about these boxes:
The possible things that can be stored inside are called values. Thus, at any given moment, a box’s value is whatever’s inside it.
Each box has a unique name:
x = y
Here, the =
(equals sign) does not mean “equals.”
It has been repurposed to mean “clone”, “copy,” or, in programming-language jargon, “assign”.
The value on the right side of the assignment operator is assigned to the variable on the left.
Important: Remember, a variable(box) can hold only one value at a time.
We’ll now start working with variables that hold integers (whole numbers like 3, 17, 2097, but not numbers like 3.141).
Consider this program:
Type up the program in variable_example.py
. What does it print?
Now let’s examine key parts of this program:
i
is the name of a “box” (of sorts). The term used for “box” is variable . i
is a variable. To put something in a variable, we use assignment with the repurposed =
(equals) sign.5
gets printedImportant: What you see on printed out is the number 5
and NOT the letter i
, thus when you see print(i)
you should think: - “Hmmm, the print function is going to print the contents of variable i
”. - “I wonder what’s inside i
?” - “Let me look in the program to see what was the most recent value that got written into i
”. For example:
Type up the above in variable_example2.py
and confirm that 3 is what gets printed.
By way of explanation:
Thus: when you make a variable, you need to put something in it.
Next, let’s look at assignment between variables: This is the analogue of cloning between “boxes”. Consider this program:
We say, in short, ” i
is assigned to j
“. Notice: we’ve used comments above to annotate and explain. We’ll do this often, knowing that comments are not executed.
The above example illustrates that the value in i
gets copied into the variable j
, which means that the value 5 is still in the variable i
.
Note that a copied value does not change if the original is changed. For example, consider:
Here’s the line-by-line execution: - The first line puts the value 5 in variable i. The second line copies the value ini
(which is 5) into j. Soj
will have the value 5 as well. - The third line replaces the value 5 with value 0. -j
still has 5, so the fourth line will print 5. - Note: 0 is an actual value, and is not “no value” or “nothing”.
Type up the following lines of code in variable_example7.py
Add some lines of code with the objective of swapping the values in variablesi
and j. You will need a third variable to be used as a holding place. Thus, without directly assigning the number 5 toj
or the number 6 to i, write code using a third variable to achieve the desired swapping of values.
Let’s examine the familiar arithmetic operators +, -, *, /
:
+
-
*
/
Consider this example with addition:
What happens during execution:
The values in i
and j
are added. The resulting value goes into variable k
.
A long-ish way of saying this aloud:
k
is assigned the sum of the values of i
and j
”A shorter way: - “k
is assigned i
plus j
”
Here’s an example with multiplication and division:
i = 5
j = 6
k = i * j
print(k) # prints 30
m = i / j
print(m) # what does this print?
n = i // j
print(n) # what does this print?
Type up the above in variable_example8.py
. Now, find values of i
and j
such that the printed output is
36
4.0
4
Save your program with these values of i
and j
.
Integer division: In math, we learned that 1/4 = 0.25 and 21/6 = 3.5. This remains true in Python when we do something like
On the other hand, if we wish to perform integer division, we can use the integer division operator:
That is, the result is truncated down to the nearest integer.
Consider the following program:
About expressions:
1
, above), and variables using operators. Example: i*j - (i+1)*(j-1)
.(i*j) - ((i+1) * (j-1))
. Here, we added some clarifying parentheses./, *, +, -
.i*j - i+1*j-1
.k = i * j - (i + 1) * (j - 1)
. But k = i*j - (i+1)*(j-1)
. is easier to read.Let’s dive a bit deeper into precedence and do some examples: - We’ll use the four operators: addition (+
), subtraction (-
), multiplication (*
), and division (/
). We’ll use small integer to illustrate. Note: The key to working them out is to use extra parentheses in the right way.
The PEMDAS rule: apply Parentheses, then Exponents, then Multiplication and Division, and then Addition and Subtraction.
Example: 3 + 2*4
2*4
to get 83 + 8
to get 11.3 + (2*4)
, can makes it more clear.Example: 3*(24/3-2*3)
First, work out what’s inside the parentheses (the P of PEMDAS):
24/3
and multiplication of 2*3 to get (8 - 6)
(2)
3 * ( (24/3) - (2*3) )
Example: 1 + ( (4 - 1) * 8) / 6
(4 -1) = 3
1 + (3 * 8) / 6
1 + 24/6
1 + 4
What does the expression \(i \cdot j - i + 1 \cdot j-1\) evaluate to when i=7
and j=3
? Write a program example_expression.py
to compute the value - your program should print the value after calculating it.
The remainder operator: The expression 10 % 3
is “the remainder when 10 is divided by 3”. Thus 10 % 3
yields 1.
Similarly 11 % 4
is 3. The remainder operator is sometimes called modulo, as in “ten modulo 3 is 1”
Consider this example:
Can you mentally execute and identify what’s printed in the code above? Type up the above in expression_example2.py
to confirm.
One way to know whether one number cleanly divides another is to apply the %
(remainder) operator.
Try running the above code. You can see that for numbers that divide evenly (10 and 2, 12 and 3), the result is 0.
Because it is common to add values into (and subtract values out of) existing variables, Python has built-in shortcut operators for these operations.
Consider this program, which
We can write this using the “shortcut addition” operator +=
as follows:
s += i
is the same as s = s + i
One can read s += i
as “add i
to what’s already in s
, and store the result in s
”.
This can be applied to the other operators as well:
So far all of the numeric variables we have worked with have been integers, whole numbers without decimals. However, it is often useful to work with decimals and fractions.
Python automatically returns a float from a mathematical operation when it is appropriate:
Write up the above as float_behavior.py
. Add a multiplication operation that results in a float.
An operation between two floats that yields a whole number still results in a float:
The distinction here is that the value displayed as 3.0
is a float, whereas something displayed as 3
would be an integer.
Because of how computers represent numbers, floating point variables are not always perfectly precise.
For instance, we know that \(1 + 2 = 3\). Python’s integer math represents this correctly:
We also know that \(0.1 + 0.2 = 0.3\). However, this is a case where Python is slightly imprecise!
Understanding and predicting the exact nature of these errors (“floating point errors”) is a complicated topic: for now, you should simply know that these errors exist.
Python has built in functions int()
and float()
to convert between these two types of numeric variables.
int()
will truncate the floating point number at the decimal point.float()
converts exactly.As you might imagine, there are many ways to inadvertently create errors. In each case below, first try to identify the error just by reading. Then, type up the program to confirm.
We’ll now see a different kind of error:
Type it up in error3.py
and see. “Fix” the error - modify the code so that the error does not occur.
The above is an example of a runtime error : The code itself is correctly written in that there are no issues with breaking the rules of the language. However, wheni
is 0, you can’t divide by 0.
Another in our series of occasional “big picture” sections that will step back from the material to comment on how we can learn better.
This was a long module with lots of exercises and details. Let’s review:
If you have to go back to some of the material to review or try some exercises again, that’s fine. You’re going to get better at this!
Full credit is 100 pts (complete at least three problems). There is no extra credit.
Add code to line 4 of following program to add x
and twice y
divide the result by 3, convert the result to an integer and assign the result to variable z
, i.e.:
\(x = \frac{x + 2 \times y}{3}\) converted to an integer.
The result will initially be a floating point number, 5.0
, which after conversion to an integer will be 5
, resulting in this printed output:
5
Submit as more_math.py