Operations
Operations on numbers
The usual arithmetic operations on numbers function in the obvious corresponding ways:
- Addition:
x + y
- Subtraction:
x - y
- Multiplication:
x * y
- Division:
x / y
Operations that the user is less likely to be familiar with are:
- Floor division:
x // y
- Mathematically, this represents \(\lfloor x/y \rfloor\) where \(\lfloor . \rfloor\) is the floor function.
- Modulus:
x % y
- This is the remainder after computing \(x/y\).
- Exponentiation:
x ** y
- Left bitshift:
x << y
- Right bitshift:
x >> y
- Bitwise AND:
x & y
- Bitwise OR:
x | y
- Bitwise XOR:
x ^ y
If the reader is unfamiliar with bitwise operations and bitshifting, that is probably fine and nonissue. Nonetheless, the curious reader should check this page.
Operations on strings
To concatenate two strings, we use the +
operation:
'Hello' + 'World'
becomes
'HelloWorld'
It is also possible to repeat a string:
'Hello'*3
becomes
'HelloHelloHello'
Order of operations
Python has a consistent order of operations. See this page.
Exercises
- Try running the following code in Python:
print(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1)
Does it give back what you expect? Why do you think you got that output? (Hint: What is the base-2 representation of 0.1?)
Find the (possibly) complex roots of \(x^2 + x + 1\) by programming the quadratic formula into Python. Verify that these are in fact roots by having Python evaluate the expression \(r^2 + r + 1\) where \(r\) is a root (Note: You will likely not get 0 but, rather, numbers very small and “close” to 0. That is perfectly fine and expected.).
The previous two exercise demonstrate the effects of “machine epsilon” when dealing with computations involving floating-point numbers. Google “machine epsilon” and try to understand the concept of it and how it plays a role in the two exercises above.
- Write code that repeats your name 5 times by multiplying the string consisting of your name by 5. You should end up with something like
"ChrisChrisChrisChrisChris"
where you replace
Chris
with your own name. The Euclidean division algorithm states that given any integers \(a\) and \(b\) with \(b\neq 0\), there exist unique integers \(q\) and \(r\) such that \[a = bq + r\] and \(0 \le r < |b|\). Write a Python program that computes the integers \(q\) and \(r\). Verify that your program computes these numbers correctly by having Python compute \(bq + r\).
- There are many cases where we may want to “concatenate” a string with something that is not a string. For instance,
print('5 + 5 = ' + (5 + 5))
This results in a runtime error. Why does that error occur? Fix the error by converting
(5 + 5)
to a string (hint: type conversions) first, then concatenating that to the string'5 + 5 = '
.