Python (2016)

CHAPTER 7: Learning How to Count—Python Integers

In the first chapter, we compared Python to ABC. Here, let us consider how Python does numbers—123.

There are two types of numbers in Python—integers and floats. Integers (“int”)here follow the same conventions we have learned in school mathematics . They are whole numbers—5, 9, -75, 5000 are all examples. Numbers with decimal points—such as 3.1416—are not integers. Instead, they are floats.

As if the distinction wasn’t easy enough to figure out, Python has a nifty tool to figure out whether a number is an integer or not. Simply use the built-in “isinstance” function to check if an item is an integer or nor:

>>> isinstance (54, int)

True

Note that all you have to do is to place the number and the term “int” inside a parenthesis after the “isinstance” function. The “int” provides the condition “isinstance” will compare against. If you get a True. Then the number is an integer. A False would mean the number is a float.

If you fancy something just a wee-bit more challenging, you can exploit the concept of integers in order to turn the shell into a calculator. Simple mathematical operations can be performed on integers—addition, subtraction, multiplication, and division (+, -, *, / respectively). For example:

>>> 10+10/2

15.0

If you have noticed in this line, Python followed the order of operations—multiplication and division first, then addition and subtraction. This is why the answer did not turn out to be 10. You will also notice that the output is a float, despite the decimal section being a 0. In Python, a float always comes out when you try to divide. Lastly, a minus sign in front of any number inverts its sign into negative.

But what if you want to divide and get a whole number as an answer? This can also be done through “floor division”. To use this feature, simply use two slashes (“//”) when typing out the problem. For example:

>>>700//7

100

Floor division works by rounding off the resulting quotient, therefore giving you a whole number—an integer—all the time.

You may also wish to get just the remainder of a division process by using the modulo feature. This can be accessed through the percent sign:

>>>1%52

1

For those wanting to solve the power of a number, two asterisks (“**”) can be used:

>>>2**5

32

Non-Decimal Integers

The numerical system that we are accustomed to using—as well as most numeral systems in the world—is ten-based. While this is a very useful way to go about our daily tasks, this isn’t often the most useful way of communicating with computers. This is why programmers commonly employ other forms of numerical systems—binary, hexadecimal, octal, etc. These numeral systems will have to be partially covered in this section, in order to gain a deeper understanding of Python’s numbers.

Let’s start with binary. This is something that most people have already heard, and yet is something that is not all too commonly understood. While it has always been inextricably linked to computer language, binary as we know it has been in use way before electricity even came into widespread use. As the word suggests, “binary” is based on the numeral 2. This means that only two numbers are used—1 and 0. This makes 1+1=10 instead of the common sense 1+1=2.

In order to use binary notations in Python, you will need to add the code “0B” or “0b” at the start of the number. For example:

>>>0B11

3

The output line gives you the decimal conversion of the binary notation that was entered. Of course, you can also do mathematical notations in binary, but the output will always be in standard decimal.

Octal numbers, on the other hand, are numbers that aren’t in as much use as the binary system. One of the biggest reasons is that the numeral system has been surpassed by the hexadecimal in computer use. Back in the time, octal made perfect sense because it can fit perfectly into three bits. However, it fails to fit into the standard 8-bit style. In case you ever need to use octals, however, it is a relief to know that Python still supports them. Octal numbers are made up of digits 0-7. In order to use the system in a line of Python code, simply add “0O” or “0o” at the beginning. The octal system behaves in just the same way that binary behaves.

>>>0o100

64

Then, there is the hexadecimal system which has been deeply ingrained in computer usage. It is especially useful since it can fit into a “nibble” (Yes, it’s an actual measure—4 bits.). Of course, two nibbles make a byte, where hexadecimal still works. The only tricky part is that hexadecimal has to use 16 characters as “digits”—and we only naturally count from 0-9. This means we are using 0-9, and adding in A-Fin order to complete a hexadecimal notation. And yes, we are using letters as numbers.

In order to work with hex numbers in Python, you will need to add the “0X” or “0x” prefix to the line of code.

>>>0xE

14

Note that you do not have to necessarily use capital letters when working with hexadecimals—the extra pinky finger movement may prove tiring. If you are more comfortable, lowercase letters would also work.

This topic of non-decimal integers might not come into play until you are in the intermediate to advanced stages of Python programming—however, it will be important to understand how to tap them now that we are in one of the most basic of Python lessons.

Python Floats

Integers may be great for many situations, but the fact that they are whole numbers can pose quite a limit on them. First of all, they are not necessarily real numbers. In mathematics, a real number is any value that will represent a quantity along one continuous line—a definition that puts fractions (in decimal forms) within its folds. This means that 3.1416 and 1.75 are both real numbers. In the field of computer science, these numbers are called “floats”. In order to test if a number is a float (despite the easy distinction), we can do similar tests to what we did for integers.

>>>isintsance (4.5, float)

True

>>>isinstance (0, float)

False

Like before, the word “True” will appear for positive matches with the “float” condition and a “false” will appear otherwise.

As a rule of thumb in Python, floats are those that have a decimal point while integers are those that do not. That the two have the exact same value is not considered—as in the case of 77.0 (float) and 77 (integer). When it comes to the arithmetic operations, the same ones we saw for integers will be applicable for floats.

Before you start playing with floats on your own, there is one other thing you need to know—floats are limited to only a certain degree of precision. This is due to Python’s (and computers’) architecture. Consider for example the following piece of code:

>>> 2+0.00000000000000000000099

2.0

As you see, the answer is still a float—however, the sum cut off all the other decimals and displayed only 2.0. This is technically fine for simple everyday computing, since the two 9s on the end are basically insignificant numbers.

Check out this other example:

>>>1.13-1.1

0.029999999999999805

This is another demonstration of how floats lose precision. Of course, the answer would be a simple 0.03. However, quirks of computer memory architecture brought out a different answer. You will notice, however, that as the minuend (the first number in a subtraction equation) increases in value, so does the answer regain precision.

Hence, when working with Python, it is important to know that there may be a margin of error when dealing with decimals.

Booleans

Students of logic will remember this. In Python as in many programming languages, a Boolean is either a True or False value. This is essentially a special data type, and is considered a subclass of integers. A Boolean has two distinct states, and only one of those states may be there at a time. Think about it—there are many different Boolean values that we work with everyday—hot or cold, on or off, light or dark.

Aside from the True or False of Booleans, there is the Boolean expression—which can take such a statement such as 1=0 and 1=1 and churn out a valuation of False and True respectively. Any empty number or data type will be judged as False, and all other will be judged as True. The “bool()” method can be used to demonstrate this:

>>>bool(“Python”)

True

>>>bool(785)

True

>>>bool(0)

False

>>>bool(“”)

False

>>>bool()

False

>>>bool(0.0000000)

True

Note that both True and False are case-sensitive—this means that you have to type them exactly as they are shown, otherwise Python will prompt you a syntax error.

Just like in logic, Python’s Boolean statements can also use operators—and, or, not. The “and” operator produces a True answer if you have all the Booleans as True—otherwise, it is False. The “or” statement will allow a True answer as long as one (or more) of the Booleans is True. If all of them are False, then a False answer will be given. Finally, “not” will reverse the Boolean partnered with it.

To see it in action, here are a few examples:

>>>not True

False

>>>False and False

False

>>>False or True

True

>>> not (True and False)

True

>>>not (False or True)

False

Complex Numbers

In mathematics, complex numbers are represented as a+bi—where both a and b are real numbers, while the i is an imaginary number (where, in turn, i2=-1). Within the world of computers—and particularly in Python—the i is denoted as j. This makes the equation a+bj. One should also note that both a and b are being treated as floats. This will be further discussed later.

>>>1+5j

(1+5j)

>>>0+2.5j

2.5j

If you will be experimenting with this, note that j is not case sensitive and so you can use the uppercase letter. You can also try extracting the real and imaginary numbers from the complex number:

>>>(2+7j).real

2.0

>>>(5+24j).imag

24.0

Note that you will either have to put the entries inside parentheses, or else you will need to store them inside a variable. If not, then you will start getting weird results.

Number Conversions

Since floats and integers cannot always be mixed together, you will have to be able to convert one to another. Thankfully, Python provides for a very easy way to do this.

Let’s start off by converting floats to integers, using the “int()” method.

>>>int(7.3)

7

>>>int(False)

0

>>>int(True)

1

You can also convert strings, though this will be discussed in better detail later.

In order to convert integers to floats instead, it’s pretty much the same—use the “float()” method.

>>>float(452)

452.0

>>>float(False)

0.0

>>>float(True)

1.0

Note that these two previously-mentioned methods cannot be used on complex numbers, or else Python will throw errors. You can get around this by extracting the real or imaginary parts of the number, through the “.real” and “.imag” methods.

You can also use a built-in Python method in order to convert data into a complex number—however, this is a bit trickier since it takes two parameters. The first one is the real number (required), and the second is an imaginary number. This is then linked by the “complex()” method.

Here are some examples:

>>>complex(True)

(1+0j)

>>>complex(1,75)

(1+75j)

>>>complex(“8”)

(8+0j)

>>>complex(“25j”)

25j

One thing that the astute reader would notice is that Python provides a code-based (method-based) way to ascertain, identify, convert, or operate on even the simplest numbers—case in point is the process of converting an integer into a float. Remember, however, that the simplest of the operations we have discussed were not meant to be used as is—they were all meant to play a part in a longer chain of codes that in turn will comprise a program.