Python/Numbers

< Python

Objective

  • Learn about Python integers.
  • Learn about non-decimal integers.
  • Learn about Python floats.
  • Learn about float's precision.
  • Learn about Boolean algebra. (Booleans are a subclass of integers.[1])
  • Learn about complex number in Python.
  • Learn how to convert numbers into different basic data types.

Lesson

Data Types

This is the first of several lessons on the data types used by Python. Computer programs can process instructions that work with many different kinds of data, and the instructions need to be very precise. If you add a word to this sentence, 'add' means something very different from when you add 2 and 3. A computer language has to have a set of rules defining what operations can be applied to different kinds of data, and for this to work, there also has to be a set of rules defining exactly what data can be used with each operation. For example, if you want to calculate grossProfit = salesIncome - costs, a program has to know that these quantities are variables containing numbers rather than just strings of letters. They must have a numerical data type rather than string data type.

If you are not clear about the meaning in computer science of variables and of data types, it may help to brush up on the lesson Introduction_to_Programming/Variables.

Python Integers

Python has several data types to represent numbers. This lesson introduces two: integers, and floating point numbers, or 'floats'. We'll discuss floats later on in the lesson. An integer, commonly abbreviated to int, is a whole number (positive, negative, or zero). So 7, 0, -11, 2, and 5 are integers. 3.14159, 0.0001, 11.11111, and even 2.0 are not integers, they are floats in Python. To test if this is true, we can use the isinstance built-in function to test if a number is or isn't an integer.

>>> isinstance(7, int)
True
>>> isinstance(0, int)
True
>>> isinstance(-11, int)
True
>>> isinstance(2, int)
True
>>> isinstance(5, int)
True
>>> isinstance(3.14159, int)
False
>>> isinstance(0.0001, int)
False
>>> isinstance(11.11111, int)
False
>>> isinstance(2.0, int)
False


We can perform simple mathematical operation with integers, like addition (+), subtraction (-), multiplication (*), and division (/). Here are some examples using simple math.

>>> 2+2
4
>>> 4-2
2
>>> 6+1
7
>>> 6+7-3
10
>>> 2*2
4
>>> 2*2*2
8
>>> -2
-2
>>> 8/2
4.0
>>> 4*4/2
8.0
>>> 4-4*2
-4
>>> 2-4
-2
>>> 10+10/2
15.0


You should have noticed three things in the above example. First, all mathematical operations follow an order of operations; multiplication and division are done first, then addition and subtraction are performed, hence why 10+10/2 didn't result in 10.0. Secondly, when you divide, a float is always the result. Lastly, by putting a minus sign (-) in front of a number, it will become a negative number.

You can do more mathematical operations than the previously demonstrated ones. We can preform a floor division by using two forward slashes (//) to divide and have the result as an integer.

>>> 4 // 2
2
>>> 1 // 8
0
>>> 5 // 5
1
>>> 100 // 5
20
>>> 4 // 3
1


Now, that may save us trouble, but what if we want to get just the remainder of a division equation? We can preform a modulo operation which will get the remainder of a number. To preform a modulo, we need to use a percent sign (%).

>>> 5 % 4
1
>>> 1 % 4
1
>>> 4 % 4
0
>>> 2 % 4
2
>>> 2 % 1
0
>>> 20 % 2
0
>>> 20 % 3
2


You can also find the power of a number by using two asterisk keys (**).

>>> 4 ** 2
16
>>> 4 ** 4
256
>>> 1 ** 11278923689
1
>>> 2 ** 4
16
>>> 10 ** 2
100
>>> 1024 ** 2
1048576
>>> 10 ** 6
1000000

Non-decimal Integers

Almost everyone is familiar with ten based numbers. While base 10 is useful for everyday tasks, it isn't ideal for use in the computer world. Three other numeral systems are commonly used in computer science; binary, octal, and hexadecimal. We'll lightly cover Python's use of these in this section. The binary system is essential as all information is represented in binary form in computer hardware. Octal and hexadecimal are convenient for condensing binary numbers to a form that is more easily read by humans, while (unlike decimal) being simple to translate to or from binary. If you have difficulty with this part of the lesson, it may help to brush up on the lesson Numeral_systems in the course Introduction_to_Computers.

Most people have heard of binary and it is often associated with computers. Actually, modern binary made its way into the world far before electricity was widely in use. The binary system is 2 based, which means that only two numbers are used. Of course, these numbers are 0 and 1. So 1+1=10, unlike the decimal's 1+1=2. To use binary numbers in python, you'll need to prepend 0B or 0b to the number.[2]

>>> 0B11
3
>>> 0B1 + 0B1
2
>>> 0B11 + 0B1
4
>>> 0B10001 + 0B1
18
>>> 0B10001 - 0B1
16


Note: In computers, a binary digit of information is called a bit.


The octal numeral system is something that really isn't used anymore, since it was superseded by hexadecimal. The octal system made sense back then, since the 8 based system can fit into three bits perfectly. Though this scheme fits into bits, it does not fit into a standard byte, which is 8 bits. Since the octal numeral system is 8 based, you can only use numbers 0-7. To use octal numbers in python, you'll need to append 0o or 0O to the beginning of the number.[3] You may find it alot easier to use a lowercase O instead of an uppercase one, since it could be confused as a zero.

>>> 0o3
3
>>> 0o12
10
>>> 0o12 + 0o10
18
>>> 0o12 - 0o03
7
>>> 0o100
64
>>> 0o777
511
>>> 0o777 - 0o111
438


The hexadecimal numeral system is widely used when working with computers, since it can fit into a nibble (4 bits). Since a standard byte is 8 bits, two nibbles could perfectly fit into a byte, hence why the octal system is rather obsolete. Hexadecimal has 16 digits, which consist of 0-9 and A-F. "Letters as numbers?", you may say. Indeed, it may be tricky working with letters as numbers, but once you get comfortable with them, it will be easy to use. To use hexadecimal numbers in python, you'll need to append 0x or 0X to the beginning of the number.[4] I suggest using a lowercase x, since it is easier to distinguish from the numbers and uppercase letters.

>>> 0xF
15
>>> 0xF0
240
>>> 0xFF - 0xF
240
>>> 0xF + 0xA
25
>>> 0x2 + 0x2
4
>>> 0x12 - 0xA
8
>>> 0xFF / 0xF
17.0
>>> 0xF * 0xF
225


Note: You do not have to use just uppercase letters when working with hexadecimal, you can also use lowercase letters if you find it easier.


This topic has been lightly brushed up on and will probably not be used until later in advanced lessons. If you feel a need to learn this, or you want to be proficient at it, the course Introduction to Computers has a lesson called Numeral systems that deals with these numeral systems with a little more in depth teaching.

Python Floats

Although integers are great for many situations, they lack one problem, integers are whole numbers. This means that they are not real numbers. A real number is a value that represents a quantity along a continuous line[5], which means that it can have fractions in decimal forms. 4.5, 1.25, and 0.75 are all real numbers. In computer science, real numbers are represented as floats. To test if a number is float, we can use the isinstance built-in function.

>>> isinstance(4.5, float)
True
>>> isinstance(1.25, float)
True
>>> isinstance(0.75, float)
True
>>> isinstance(3.14159, float)
True
>>> isinstance(2.71828, float)
True
>>> isinstance(1.0, float)
True
>>> isinstance(271828, float)
False
>>> isinstance(0, float)
False
>>> isinstance(0.0, float)
True


As a general rule of thumb, floats have a decimal point and integers do not have a decimal point. So even though 4 and 4.0 are the same number, 4 is an integer while 4.0 is a float.

The same basic arithmetic operations used for integers will also work for floats.

>>> 4.0 + 2.0
6.0
>>> -1.0 + 4.5
3.5
>>> 1.75 - 1.5
0.25
>>> 4.13 - 1.1
3.03
>>> 4.5 // 1.0
4.0
>>> 4.5 / 1.0
4.5
>>> 4.5 % 1.0
0.5
>>> 7.75 * 0.25
1.9375
>>> 0.5 * 0.5
0.25
>>> 1.5 ** 2.0
2.25


The Precision of Floats

Before you start calculating with floats you should that the precision of float has limits, due to Python and the architecture of a computer. Some examples of error due to finite precision are displayed below.

>>> 1.13 - 1.1
0.029999999999999805
>>> 0.001 / 11.11
9.000900090009002e-05
>>> 1 + .0000000000000001
1.0


In the first example, 1.13 - 1.1 = 1.03, although Python comes to the conclusion that the real answer is 0.029999999999999805. The fact behind this reasoning is based on how the computer stores memory, so the difference lost a little of its precision. As the minuend increase in size, so does its precision. 2.13 - 1.1 = 1.0299999999999998 and 3.13 - 1.1 = 2.03.

In the second example, 0.001 / 11.11 = 9.000900090009002e-05 where e-05 means ten to the power of negative five. The answer could also be 9.000900090009001e-05 depending on how the quotient is rounded, how long the quotient can be stored on the computer, and the most significant number on the right hand side.

In the third example, the sum of the addends 1 + .0000000000000001 = 1.0 although we know that it really is 1 + .0000000000000001 = 1.0000000000000001. The reason the second addend is left is out is because of its insignificance. Although this might not matter for every day situations, it may be important for such uses as rocket science and possibly calculus.

When working with Python floats, we need to be aware that there will probably be a margin of error.

The Boolean

In Python and most languages, a Boolean can either be True or False. A Boolean is a special data type and is a subclass of int.[6] Since a Boolean have two states and only one at a time, a Boolean creates a special relationship between things. We can think of some Boolean values that we deal with in real life for, example, on and off, hot and cold, light or darkness, and etc. Although a Boolean can be True and False a Boolean expression can take a statement, like 1 = 1 and 1 = 0, and turn it into a Boolean, True for the first and False for the later. We can use the bool() method to check the Boolean value of an object, which will be False for integer zero and for objects (numerical and other data types) that are empty, and True for anything else.

>>> 1 == 1
True
>>> 1 == 0
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(10001219830)
True
>>> bool(-1908)
True
>>> bool("Hello!")
True
>>> bool("")
False
>>> bool(None)
False
>>> bool(0.000000000000000000000000000000000)
True
>>> bool(0.0)
False
>>> bool([])
False
>>> bool([1, 2, 3])
True
>>> bool()
False
>>> bool(True)
True
>>> bool(False)
False
>>> bool(1==1)
True
>>> bool(1==0)
False


Note: True and False are both case-sensitive, which means that you must type them exactly as shown, otherwise you'll get a syntax error.

You can also use there operators to alter a Boolean statement[7]; or, and, not. You can use an or statement to allow one or more Booleans to be False so long as one is True. And and statement requires all of the Booleans to be True for it be True. The not statement reverses a Boolean so not True is False and not False is True. Here's some examples:

>>> not False
True
>>> not True
False
>>> True and True
True
>>> True and False
False
>>> True or False
True
>>> False or False
False
>>> not(False or False)
True
>>> not(False and False)
True
>>> not(False and True)
True

Complex Numbers

A complex number is represented as a+bi where a and b are real numbers, like 7 or 12, and i is an imaginary number, where i² = -1. In the computer field, and in the world of Python, i is denoted as j for technical reasons, so we use a+bj. It should also be noted that a and b are both treated as floats. This subject will be briefly covered until later lessons.

>>> 1+2j
(1+2j)
>>> -1+5.5j
(-1+5.5j)
>>> 0+5.5j
5.5j
>>> 2j
2j
>>> 1+0j
(1+0j)

Note also that j cannot be used on its own without b. If you try to use j on its own, Python will look for a variable j and use the value of that variable, or report an error if the variable is not known or a wrong type. So the imaginary number i or j must always be written as 1j.

>>> a = 5 + 3j
>>> a - j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> a - 1j
(5+2j)
>>> j = -3j
>>> a - j
(5+6j)
>>> a - 1j
(5+2j)

The last result illustrates that even when the variable j has a numerical value, 1j (where, as above, can be any number) is always interpreted as the imaginary number j, not the variable j.

Note: the imaginary number, j, isn't case-sensitive, so you can use j or J.


You can extract the real number and the imaginary number by using .real and .imag respectively.

>>> (1+2j).real
1.0
>>> (1+2j).imag
2.0
>>> var = 5+3j
>>> var.real
5.0
>>> var.imag
3.0


Note:You'll get weird results if you don't use parentheses on a real number that isn't stored in a variable.

Number Conversions

Since integers and floats can't be mixed together in some situations, you'll need to be able to convert them from one type to another. Luckily, it's very easy to preform a conversion. To convert a data type to an integer, you'll need to use the int() method.

>>> int(1.5)
1
>>> int(10.0)
10
>>> int(True)
1
>>> int(False)
0


You can even convert strings, which you'll learn about later.

>>> int("100")
100


To convert a data type to a float, you'll need to use the float() method. Like the integer, you can convert strings to floats.

>>> float(102)
102.0
>>> float(932)
932.0
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("101.42")
101.42
>>> float("4")
4.0


Note: You cannot use any of the above conversions on a complex number, as it will throw an error. You can work around this by using .real and .imag


You can also use the bool() method to convert a data type to a Boolean.

>>> bool(1)
True
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(0.01)
True
>>> bool(14)
True
>>> bool(14+3j)
True
>>> bool(3j)
True
>>> bool(0j)
False
>>> bool("")
False
>>> bool("Hello")
True
>>> bool("True")
True
>>> bool("False")
True


Note: Notice that bool("False") is True. Unlike int() and float(), when bool() converts a string, it checks to see if the string is empty or not.


Converting a data type to a complex is a little more tricky, but still easy. All you need to do is use the method complex() although it takes two parameters, one of which is optional. The first parameter is the real number, which is required, and the second parameter is the imaginary number, which is optional.

>>> complex(True)
(1+0j)
>>> complex(False)
0j
>>> complex(3, 1)
(3+1j)
>>> complex(1, 22/7)
(1+3.142857142857143j)
>>> complex(0, 1.5)
1.5j
>>> complex(7, 8)
(7+8j)
>>> complex("1")
(1+0j)
>>> complex("1+4j")
(1+4j)
>>> complex("9.75j")
9.75j

Assignments

  • Play around with the python interpreter using integers, floats, Booleans, and complex number.
  • Critical think about integers and floats. When should you use integers? When should you use floats?
  • A loss of significance for a float value should be expected when working with insignificant numbers. When would this become a problem?

Completion status: Ready for testing by learners and teachers. Please begin!

References

This article is issued from Wikiversity - version of the Saturday, April 02, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.