We’ve seen some basic mathematical expressions with Python, simple addition and the like, in previous guides (here and here). Now let’s expand on that, and see just how powerful Python is as a calculator. You can work within the IDLE Shell, or in the Editor, whichever you like.
Step 1 – Open up the GUI version of Python 3, as mentioned you can use either the Shell or the Editor. For the time being, we’re going to use the Shell. If you’ve opted to use a third-party text editor, note that you need to get to the IDLE Shell for this part of the tutorial.
Step 2 – In the Shell enter the following:
As you can see, Python can handle some quite large numbers.
Step 3 – You can use all the customary Mathematical operations: divide, multiply, brackets and so on. Practise with a few, for example:
Step 4 – As you’ve no doubt noticed, division produces a decimal number. In Python, these are called floats, or floating point arithmetic. If however, you need an integer as opposed to a decimal answer, then you can use a double slash:
and so on.
Step 5 – You can also use an operation to see the remainder left over from division. For example:
will display 3.333333333, which is, of course, 3.3-recurring. If you now enter:
This will display 1, which is the remainder left over from dividing 10 by 3.
Step 6 – Next up we have the power operator, or exponentiation if you want to be technical. To work out the power of something you can use a double multiplication symbol, or double-star on the keyboard:
Essentially, it’s 2x2x2, but we’re sure you already know the basics behind maths operators. This is how you would work it out in Python.
Step 7 – Numbers and expressions don’t stop there. Python has numerous built-in functions to work out sets of numbers, absolute values, complex numbers, and a host of Mathematical expressions and Pythogarian tongue-twisters. For example, to convert a number to binary, use:
Step 8 – This will be displayed as ‘0b11’, converting the integer into binary, and adding the prefix 0b to the front. If you want to remove the 0b prefix, then you can use:
The Format command converts a value, the number 3, to a formatted representation as controlled by the format specification, the ‘b’ part.
Step 9 – A Boolean Expression is a logical statement that will either be true or false. We can use these to compare data, and test to see if it’s equal to, less than, or greater than. Try this in a New File:
a = 6
b = 7
print(1, a == 6)
print(2, a == 7)
print(3, a == 6 and b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a == 7 or b == 7)
print(7, a == 7 or b == 6)
print(8, not (a == 7 and b == 6))
print(9, not a == 7 and b == 6)
Step 10 – Execute the code from Step 9, and you’ll see a series of True or False statements depending on the result of the two defining values: 6 and 7. It’s an extension of what we’ve looked at, and an important part of programming.