Numbers

Tutorial created by Mohsin Haider, at www.mohsinhaider.com, for the CodeMoh computer science initiative.

In Python, all constructs are objects, even numbers. Python has many types of objects and data structures built into the language. Within this section, we will cover the following:

 1. Object Assignment
 2. Arithmetic operators and int and float
 3. Using the conversion functions
 4. Floating-point Inaccuracy
 5. Print function

Object Assignment (Numbers, Specifically)

Assigning variables in Python is no different than you would expect. Use the "=" (equals) operator to give variables values. In Python, all variables are dynamically typed - so there is no explicit type declaration needed. Remember that, in Python, all variables are objects. This allows us to use the terminology interchangeably.


In [93]:
# Create an object called "foo" and assign it the value 9.
foo = 9

Jupyter Notebooks are know to be REPL environments. This simply means that the notebooks serve as "interactive" programming environments, where calculations or other processes can be done impromptu. REPL stands for Read-Evaluate-Print-Loop.


In [94]:
# Try running this block!
foo + 5


Out[94]:
14

In [95]:
# Evaluate the variable itself
foo


Out[95]:
9

We can use declaration constructs that contain a variable name twice. This allows a programmer to update variables as they place. When the variable that appears twice is on the right of the "=" operator, it is using whatever value it held from the last assignment. If there are other operators, like the "+" addition operator, then the calculation will be done first, then stored/updated into the variable.


In [96]:
# Here, foo has the value of 9. Let's add 9 to it.
foo = foo + 9
foo


Out[96]:
18

As you can see, the foo that is to the right of the "=" operator has the value of 9 currently (as we defined before). We added 9 to it, and then updated it by setting it to "foo =". Note that the previous "foo + 5" we did did NOT store foo again, and so the value of foo never changed.

Additionally, it is important to understand the naming convention of variables in Python. Stick to these conventions, and all will sail well:

  1. All characters in a variable name should be lowercase.
  2. No spaces in variable names, use the underscore "_", instead.
  3. Don't use traditional keyboard symbols in your names.

In [97]:
# Correct variable names
building_height = 100
water = 4

result = building_height + water

Arithmetic Operators

Before discussing numbers, let's briefly look at the simple concept of using arithmetic operators. Arithmetic operators what you would expect, +, -, *, / and //. Division is a special case, which we'll look at.


In [98]:
# Addition
3 + 15


Out[98]:
18

In [99]:
#Subtraction
9 - 3


Out[99]:
6

In [100]:
#Multiplication
3 * 4


Out[100]:
12

Division has two forms in Python 3 (and 2): divison and integer division. In Python, to get the full decimal number of a division operation, simply specify a single '/'. To specifiy integer division (drop the remainer, don't round), alternatively specify a '//'.


In [101]:
# Division
15 / 3


Out[101]:
5.0

In [102]:
# Integer Division
15 // 3


Out[102]:
5

In [103]:
# Division
9 / 4


Out[103]:
2.25

In [104]:
# Integer Division
9 // 4


Out[104]:
2
There is another arithmetic operator you should know: modulo. The "%", or modulo operator, finds the remainder of the division of its operands.

In [105]:
# Modulo
3 % 2


Out[105]:
1

Types of Numbers (int and float)

Python has two main types of numbers: integer and floating-point types. In general, int types do not have decimals, and floating-point types do.


In [106]:
# Integer
a = 3

In [107]:
# floating-point
b = 3.0

Whenever you add two integers together, you will end up with an integer. Same applies to floats. However, you if you add a float and an integer together, it will always become a float. This process is called automatic type conversion.


In [108]:
# Adding two integers
2 + 3


Out[108]:
5

In [109]:
# Adding two doubles
9.1 + 3.0


Out[109]:
12.1

In [110]:
# Adding an integer and float (automatic type conversion)
4 + 11.3


Out[110]:
15.3

In [111]:
2.1 + .9


Out[111]:
3.0

Conversion Functions

You can convert numbers back and forth from integer to floating-point using the conversion functions int() and float().


In [118]:
# Converts the argument (3) which is an integer, and spits out a float (3.0) in the REPL.
float(3)


Out[118]:
3.0

In [122]:
# Coverts the argument (5.9) which is a float, and spits out an integer (5) in the REPL.
# Note: truncation, not rounding.
int(5.9)


Out[122]:
5

Floating-point Inaccuracy

Just remember: floating-point types are never used to for any type of calculation that requires accuracy. Why is this? Take a look at the example below.


In [112]:
# Let's add 0.1 and 0.2, to get 0.3.
result = 0.1 + 0.2
result


Out[112]:
0.30000000000000004

In [113]:
# This operation should return 16.3
7.6 + 8.7


Out[113]:
16.299999999999997

The result was not what we expected. Why can't the interpreter get this right? Simply put, it is because computers have their number systems represented in base-2, while we typically use base 10. There are some numbers that are easy to represent in base-10 that are impossible to accurately represent in base-2, and vice-versa.

What does this mean to you, as the programmer? Whenever you are doing critical calculations that rely on accuracy, use the Decimal module. Below, I've imported the decimal module (more on modules later) and then I've checked what the current precision is. Right now, it's not at what we want. We change the precision, and then follow through wil the calculation


In [92]:
import decimal

# We use the 'decimal' word as the module name, and use the "getcontext" function that is a part of the module, and
# set it's .prec value (precision) to 3 decimal places.
decimal.getcontext().prec=3

# We use what's called a print() function to literally print our result to the screen (similar to the REPL behavior)
print(decimal.Decimal(0.1) + decimal.Decimal(0.2))


0.300

Print functions are something you'll use a lot. Because we're in the REPL, we can just evaluate variables by typing them out. However, from now on, we will always print whatever we to see the REPL to output. For our purposes, it is essentially the same thing.


In [116]:
# printing a number calculation
print(4 + 3)
# printing a number
print(11)
# printing a word (more on "strings" later)
print("Hello, there!")


7
11
Hello, there!

Python 2 vs Python 3 in Printing

Note: Python 2 and 3 have a few differences, as we've discussed before. One of them is printing. In Python 2, you used to print using print statements (and not functions, like in Python 3). In simple terms, by allowing print to become a function, the Python Foundation has given more capabilities to it that we will talk more later about. For now, note the syntactical difference:

print 'hello' instead of print('hello') print 1 + 3 instead of print(1 + 3)