Text stringlengths 1 9.41k |
|---|
Write down an expression that
might provide some evidence.
2. |
Why do you think 1 / 1 evaluates to 1.0 (a float) and not just 1
(an integer)?
###### More on operations
So far, we’ve seen some simple expressions involving literals, operators,
and parentheses. |
We’ve also seen examples of a few types: integers,
floating-point numbers (“floats” for short), strings, and Booleans.
We’ve seen that we can perform arithmetic operations on numeric
types (integers and floats).
###### The operators + and * applied to strings
Certain arithmetic operators behave differently when their... |
For example,
```
>>> 'Hello' + ', ' + 'World!'
'Hello, World!'
```
This is an example of operator overloading, which is just a fancy way
of saying that an operator behaves differently in different contexts. |
In
this context, with strings as operands, + doesn’t perform addition, but
instead performs concatenation. |
Concatenation is the joining of two or
more strings, like the coupling of railroad cars.
We can also use the multiplication operator * with strings. |
In the
context of strings, this operator concatenates multiple copies of a string
together.
```
>>> 'Foo' * 1
'Foo'
>>> 'Foo' * 2
'FooFoo'
>>> 'Foo' * 3
'FooFooFoo'
```
What do you think would be the result of the following?
```
>>> 'Foo' * 0
```
This gives us '' which is called the empty string and is ... |
Notice that the result is
still a string, albeit an empty one.
-----
###### 4.3 Augmented assignment operators
As a shorthand, Python provides what are called augmented assignment
operators. |
Here are some (but not all):
augmented assignment similar to
```
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
```
A common example is incrementing or decrementing by one.
```
>>> a = 0
>>> a += 1
>>> a
1
>>> a += 1
>>> a
2
>>> a -= 1
>>> a
1
>>> a -= 1
>>> a... |
Here we will
present two additional operations which are closely related: the modulo
or “remainder” operator, and what’s variously called “quotient”, “floor
division”, “integer division” or “Euclidean division.”[6]
Chances are, when you first learned division in primary school, you
learned about Euclidean (floor) divi... |
For example, 17 ÷ 5 = 3 r 2, or
21 ÷ 4 = 5 r 1. |
In the latter example, we’d call 21 the dividend, 4 the
divisor, 5 the quotient, and 1 the remainder.
5The table above says “similar to” because, for example, a += b isn’t exactly the
same as a = a + b. |
In augmented assignment, the left-hand side is evaluated before
the right-hand side, then the right-hand side is evaluated and the result is assigned
to the variable on the left-hand side. |
There are some other minor differences.
6Euclid had many things named after him, even if he wasn’t the originator
(I guess fame begets fame). |
Anyhow, Euclid was unaware of the division algorithm
you’re taught in primary school. |
Similar division algorithms depend on the positional
system of Hindu-Arabic numerals, and these date from around the 12th Century CE.
The algorithm you most likely learned, called “long division”, dates from around
1600 CE.
-----
Obviously the operations of finding the quotient and the remainder
are closely related. |
For any two integers 𝑎, 𝑏, with 𝑏≠0 there exist
unique integers 𝑞 and 𝑟 such that
𝑎= 𝑏𝑞+ 𝑟
where 𝑞 is the Euclidean quotient and 𝑟 is the remainder.
Furthermore, 0 ≤𝑟< |𝑏|, where |𝑏| is the absolute value of 𝑏. |
This should
be familiar.
Just in case you need a refresher:
-----
###### Python’s // and % operators
Python provides us with operators for calculating quotient and remainder. |
These are // and %, respectively. |
Here are some examples:
```
>>> 17 // 5 # calculate the quotient
3
>>> 17 % 5 # calculate the remainder
2
>>> 21 // 4 # calculate the quotient
5
>>> 21 % 4 # calculate the remainder
1
```
You may ask: What’s the difference between the division we saw earlier, /, and floor division with //? |
The difference is that / calculates the
quotient as a decimal expansion. |
Here’s a simple comparison:
```
>>> 4 / 3
1.3333333333333333 # three goes into four 1 and 1/3 times
>>> 4 // 3 # calculates Euclidean quotient
1
>>> 4 % 3 # calculates remainder
1
###### Common questions
```
**What happens when the divisor is zero?**
Just as in mathematics, we cannot divide by zero in Py... |
So
all of these operations will fail if the right operand is zero, and Python
will complain: ZeroDivisionError.
**What happens if we supply floating-point operands to // or %?**
In both cases, operands are first converted to a common type. |
So if
one operand is a float and the other an int, the int will be implicitly
converted to a float. |
Then the calculations behave as you’d expect.
-----
```
>>> 7 // 2 # if both operands are ints, we get an int
3
>>> 7.0 // 2 # otherwise, we get a float...
3.0
>>> 7 // 2.0
3.0
>>> 7.0 // 2.0
3.0
>>> 7 % 2 # if both operands are ints, we get an int
1
>>> 7.0 % 2 # otherwise, we get a float...
... |
The other
trips some folks up at first.
```
>>> 5 % 7
5
```
That is, seven goes into five zero times and leaves a remainder of five.
So if 𝑚< 𝑛, then m % n yields m.
**What if the divisor is negative?**
What is m % n, when 𝑛< 0? |
This might not work the way you’d expect
at first.
```
>>> 15 // -5
-3
>>> 15 % -5
0
```
So far, so good. |
Now consider:
-----
```
>>> 17 // -5
-4
>>> 17 % -5
-3
```
Why does 17 `//` `-5 yield -4 and not -3? |
Remember that this is`
what’s called “floor division.” What Python does, is that it calculates
the (floating-point) quotient and then applies the floor function.
The floor function is a mathematical function which, given some number 𝑥, returns the largest integer less than or equal to 𝑥. |
In mathematics
this is written as:
⌊𝑥⌋.
So in the case of 17 `//` `-5, Python first converts the operands to`
```
float type, then calculates the (floating-point) quotient, which is −3.4
```
and then applies the floor function, to yield −4 (since -4 is the largest
integer less than or equal to -3.4).
This also make... |
This preserves the equality
𝑎= 𝑏𝑞+ 𝑟
17 = (−5 × −4) + (−3)
17 = 20 −3.
**What if the dividend is negative?**
```
>>> -15 // 5
-3
>>> -15 % 5
0
```
So far so good. |
Now consider:
```
>>> -17 // 5
-4
>>> -17 % 5
3
```
Again, Python preserves the equality
𝑎= 𝑏𝑞+ 𝑟
−17 = (5 × −4) + 3
−17 = −20 + 3.
Yeah. I know. |
These take a little getting used to.
**What if dividend and divisor both are negative?**
Let’s try it out—having seen the previous examples, this should come as
no surprise.
-----
```
>>> -43 // -3
14
>>> -43 % -3
-1
```
Check this result:
𝑎= 𝑏𝑞+ 𝑟
−43 = (−3 × 14) + (−1)
−43 = −42 −1
The % operator ... |
It is a great
tool to further your understanding.
###### 4.5 Modular arithmetic
Now, in the Python documentation[7], you’ll see // referred to as floor
division. |
You’ll also see that % is referred to as the modulo operator.
It’s fine to think about % as the remainder operator (with the provisos
noted above), but what is a “modulo operator”?
Let’s start with the example of clocks.
**Figure 4.1: Clock face**
Perhaps you don’t realize it, but you do modular arithmetic in your
he... |
For example, if you were asked what time is 5 hours
after 9 o’clock, you’d answer 2 o’clock. You wouldn’t say 14 o’clock.[8]
This is an example of modular arithmetic. |
In fact, modular arithmetic is
sometimes called “clock arithmetic.”
[7https://docs.python.org/3/reference/expressions.html](https://docs.python.org/3/reference/expressions.html)
8OK. |
Maybe in the military or in Europe you might, but you get the idea. We
have a clock with numbers 12–11, and 12 hours brings us back to where we started
(at least as far as the clock face is concerned). |
Notice also that the arithmetic is the
same for an analog clock face with hands and a digital clock face. |
This difference
in interface doesn’t change the math at all, it’s just that visually things work out
nicely with the analog clock face.
-----
**Figure 4.2: Clock arithmetic: 5 + 9 ≡2 (mod 12)**
In mathematics, we would say that 5 + 9 is congruent to 2 modulo 12,
and we’d write
5 + 9 ≡2 (mod 12)
So 5 + 9 = 14 and ... |
Suppose we have some positive integer, 𝑛, which we call the modulus. We can perform arithmetic
with respect to this integer in the following way. |
When counting, when
we reach this number we start over at 0. |
Now in the case of clocks, this
positive integer is 12, but it needn’t be—we could choose any positive
integer.
For example, with 𝑛= 5, we’d count
0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, …
Notice that we never count to 5, we start over at zero. |
You’ll see that the
clocks in the figures above don’t have twelve on their face but instead
have zero. |
If 𝑛= 5, then we’d have 5 positions on our “clock”, numbered
0 through 4.
Under such a system, addition and subtraction would take on a new
meaning. |
For example, with 𝑛= 5, 4 + 1 ≡0 (mod 5),
4 + 2 ≡1 (mod 5),
4 + 3 ≡2 (mod 5),
and so on.
Things work similarly for subtraction, except we proceed anticlockwise. |
For example 1 −3 ≡3 (mod 5).
The same principle applies to multiplication: 2 × 4 ≡3 (mod 5) and
3 × 3 ≡4 (mod 5).
-----
##### 0
4
1
3 2
**Figure 4.4: A “clock” for (mod 5)**
##### 0
4
1
3 2
**Figure 4.5: 4 + 1 ≡0 (mod 5)**
##### 0
4
1
3 2
**Figure 4.6: 4 + 2 ≡1 (mod 5)**
-----
##### 0
4
... |
What happens when the modulus is negative?
To preserve the “direction” of addition (clockwise) and subtraction
(anti-clockwise), if our modulus is negative we number the face of the
clock anti-clockwise.
Examples:
1 ≡−4 (mod −5)
2 ≡−3 (mod −5)
2 + 4 ≡−4 (mod −5)
We can confirm these agree with Python’s evaluation of th... |
Because % has higher precedence
than +. |
Again, try inputting your own expressions into the Python shell.
**Some things to note**
- If the modulus is an integer, 𝑛> 0, then the only possible remainders are [0, 1, ..., 𝑛−1].
- If the modulus is an integer, 𝑛< 0, then the only possible remainders are [𝑛+ 1, ..., −1, 0].
**What now?**
This is actual... |
That’s all outside the scope
of this textbook. |
Practically, however, there are abundant applications
for modular arithmetic, and this is something we’ll see again and again
in this text.
Some applications for modular arithmetic include:
- Hashing function
- Cryptography
- Primality and divisibility testing
- Number theory
Here are a couple of simple examp... |
If a carton holds 12 eggs, how many complete cartons
can she make and how many eggs will be left over?
-----
```
EGGS_PER_CARTON = 12
cartons = n // EGGS_PER_CARTON
leftover = n % EGGS_PER_CARTON
###### Example: even or odd
```
Given some integer 𝑛 is 𝑛 even or odd?
```
if n % 2 == 0:
print(f'{n} is... |
We’ll get to that in due
course.)
###### Comprehension check
1. Given some modulus, 𝑛, an integer, and some dividend, 𝑑, also an
integer, what are the possible values of d % n if
a. 𝑛= 5
b. |
𝑛= −4
c. 𝑛= 2
d. 𝑛= 0
2. Explain why, if the modulus is positive, the remainder can never
be greater than the modulus.
3. The planet Zorlax orbits its sun every 291 1/3 Zorlaxian days. |
Thus,
starting from the year 1, every third year is a leap year on Zorlax.
So the year 3 is a leap year. The year 6 is a leap year. The year 273
is a leap year. |
Write a Python expression which, given some integer
𝑦 greater than or equal to 1 representing the year, will determine
whether 𝑦 represents a Zorlaxian leap year.
4. |
There’s a funny little poem: Solomon Grundy— / Born on a Monday, / Christened on Tuesday, / Married on Wednesday, / Took
ill on Thursday, / Grew worse on Friday, / Died on Saturday, /
Buried on Sunday. |
/ That was the end / Of Solomon Grundy.[9]
How could this be? Was Solomon Grundy married as an infant?
Did he die before he was a week old? What does this have to do
with modular arithmetic? |
What if I told you that Solomon Grundy
was married at age 28, and died at age 81? Explain.
9First recorded by James Orchard Halliwell and published in 1842. |
Minor changes
to punctuation by the author.
-----
###### 4.6 Exponentiation
Exponentiation is a ubiquitous mathematical operation. |
However, the
syntax for exponentiation varies between programming languages. In
some languages, the caret (^) is the exponentiation operator. |
In other languages, including Python, it’s the double-asterisk (**). |
Some languages
don’t have an exponentiation operator, and instead they provide a library
function, pow().
The reasons for these differences are largely historical. |
In mathematics, we write an exponent as a superscript, for example, 𝑥[2]. |
However,
keyboards and character sets don’t know about superscripts,[10] and so
the designers of programming languages had to come up with different
ways of writing exponentiation.
```
** was first used in Fortran, which first appeared in 1957. |
This is the
```
operator which Python uses for exponentiation.
For the curious, here’s a table with some programming languages and
the operators or functions they use for exponentiation.
`**` Algol, Basic, Fortran, JavaScript, OCaml, Pascal, Perl,
**Python, Ruby, Smalltalk**
`^` J, Julia, Lua, Mathematica
`pow()` C... |
This
is an infix operator, meaning that the operator appears between its two
operands. As you’d expect, the first operand is the base, and the second
operand is the exponent or power. |
So,
```
b ** n
```
implements 𝑏[𝑛].
Here are some examples,
Area of a circle of a given radius `3.14159 * radius ** 2`
Kinetic energy, given mass and velocity `(1 / 2) * m * v ** 2`
Also, as you’d expect, ** has precedence over * so in the above examples, radius ** 2 and v ** 2 are calculated before multiplicati... |
But they’re not understood as numbers and
aren’t useful in programming.
-----
###### But wait! |
There’s more!
You’re going to find out sooner or later, so you might as well know now
that Python also has a built-in function pow(). |
For our purposes, **
and pow() are equivalent, so you may use either. |
Here’s a session at the
Python shell:
```
>>> 3 ** 2
9
>>> 3.0 ** 2
9.0
>>>
>>> pow(3, 2)
9
>>> pow(3.0, 2)
9.0
```
With two operands or arguments, ** and pow() behave identically. |
If
both operands are integers, and the exponent is positive, the result will
be an integer. |
If one or more of the operands is a float, the result will be
a float.
Negative or fractional exponents behave as you’d expect.
```
>>> 3 ** 0.5 # Calculates the square root of 3
1.7320508075688772
>>> 3 ** -1 # Calculates 1 / 3
0.3333333333333333
```
No surprises here.
###### 𝑥[0] = 1
Remember from algebra... |
If that weren’t the case, what would become of this rule?
𝑏[𝑚+𝑛] = 𝑏[𝑚] × 𝑏[𝑛]
So 𝑥[0] = 1 for all non-zero 𝑥. |
Python knows about that, too.
```
>>> 1 ** 0
1
>>> 2 ** 0
1
>>> 0.1 ** 0
1.0
```
What about 0[0]? Many mathematics texts state that this should be undefined or indeterminate. |
Others say 0[0] = 1. |
What do you think Python
does?
-----
```
>>> 0 ** 0
1
```
So, Python has an opinion on this.
Now, go forth and exponentiate!
###### A little puzzle
Consider the following Python shell session:
```
>>> pow(-1, 0)
1
>>> -1 ** 0
-1
```
What’s going on here? |
The answer we get using pow() is what we’d expect.
Shouldn’t these both produce the same result? |
Can you guess why these
yield different answers?
###### 4.7 Exceptions
**Exceptions are errors that occur at run time, that is, when you run your**
code. |
When such an error occurs Python raises an exception, prints a
message with information about the exception, and then halts execution.
Exceptions have different types, and this tells us about the kind of error
that’s occurred.
If there is a syntax error, an exception of type SyntaxError is raised.
If there is an indent... |
These errors occur before your code is ever
```
run—they are discovered as Python is first reading your file.
Most other exceptions occur as your program is run. |
In these cases,
the message will include what’s called a traceback, which provides a little
information about where in your code the error occurred. |
The last line
in an exception message reports the type of exception that has occurred.
It’s often helpful to read such messages from the bottom up.
What follows are brief summaries of the first types of exceptions you’re
likely to encounter, and in each new chapter, we’ll introduce new exception types as appropriate.
`... |
Example:
```
>>> 1 + / 1
File "<stdin>", line 1
1 + / 1
^
SyntaxError: invalid syntax
```
-----
Notice that the ^ character is used to indicate the point at which the
error occurred.
Here’s another:
```
>>> True False
File "<stdin>", line 1
True False
^
SyntaxError: invalid syntax... |
Code which includes a
syntax error cannot be executed by the Python interpreter, and syntax
errors must be corrected before your code will run.
```
NameError
```
A NameError occurs when we try to use a name which is undefined. |
There
must be a value assigned to a name before we can use the name.
Here’s an example of a NameError:
```
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
```
Notice that Python reports the NameError and informs you of the name
you tried t... |
The
associated value is a string giving details about the type mismatch.”[11]
For example, we can perform addition with operands of type int using
the + operator, and we can concatenate strings using the same operator,
but we cannot add an int to a str.
```
>>> 2 + 2
4
>>> 'fast' + 'fast' + 'fast'
'fastfastfas... |
This will vary on a case-by-case
basis.
Here are some other examples of TypeError:
```
>>> 'hopscotch' / 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> 'barbequeue' + 1
Traceback (most recent call last):
File "<s... |
Since the remainder operation (%) and integer
(a.k.a. |
floor) division (//) depend on division, the same restriction applies
to these as well.
[11https://docs.python.org/3/library/exceptions.html#TypeError](https://docs.python.org/3/library/exceptions.html#TypeError)
-----
```
>>> 1000 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
... |
Once you’ve worked out what you think
the evaluation should be, check your answer using the Python shell.
a. 13 + 6 - 1 * 7
b. (17 - 2) / 5
c. -5 / -1
d. 42 / 2 / 3
e. 3.0 + 1
f. 1.0 / 3
g. |
2 ** 2
h. 2 ** 3
i. 3 * 2 ** 8 + 1
**Exercise 02**
For each of the expressions in exercise 01, give the type of the result of
evaluation. |
Example: 1 + 1 evaluates to 2 which is of type int.
**Exercise 03**
What is the evaluation of the following expressions?
a. 10 % 2
b. 19 % 2
c. 24 % 5
d. |
-8 % 3
-----
**Exercise 04**
What do you think would happen if we were to use the operands we’ve
just seen with non-numeric types? |
For example, what do you think would
happen if we were to enter the following. Then check your expectations
using the Python interpreter. Any surprises?
a. 'Hello' + ', ' + 'World!'
b. |
'Hello' * 3
c. True * True
d. True * False
e. False * 42
f. -True
g. |
True + True
**Exercise 05**
What is the difference between the following statements?
```
it_is_cloudy_today = True
it_will_rain_tomorrow = 'True'
```
**Exercise 06**
Some operands don’t work with certain types. |
For example, the following
will result in errors. Try these out at a prompt, and observe what happens.
Make a note of the type of error which occurs.
a. 'Hello' / 3
b. -'Hello'
c. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.