In the previous chapter, I gave you a brief introduction to using numbers in Python, creating, and storing them and the different types of numbers you can play around with.
Let us look at how to play with those numbers in this chapter by looking at how to use your numbers to do calculations and how to have real fun with Python’s pre-defined number methods.
Get your numbers out to play
We’ve looked at creating numbers and storing them and the different types of numbers in Python. But we haven’t done anything with them yet, have we?
Would you like to finally play with your numbers? Yes!
You can do pretty much everything you do in Math in Python as well. You can add two numbers or more, multiply numbers, divide them, subtract them, and it doesn't stop there! You can do a little bit more than the usual calculations. What fun is programming if you’re stuck doing the same old calculations?
You have operators that can find the remainder of a division. Yes, you read that right. You won’t have to find remainders using a long-drawn-out process anymore. I bet your calculator doesn’t do that!
You can do exponentiation as well. Want to find the result of 5 * 5 * 5? That is 5 to the power of 3. Python has a single operator you can use to do that. What more? Make the number and power as big as you want, and you’ll still get your result immediately.
Basic Math operations
Without further ado, let’s look at all the operations you can play around with in Python. I’ll be explaining how the operators work with examples for each. Clear out your numbers.py file or create a new script file.
Cross-verify with your calculator. I’m sure that’s the correct answer. As you can see, you can add more than one number. You can also change the value of your variable by doing calculations with its current value and re-storing (it’s called re-assigning in programming) it back to that variable.
We’ve learned addition in Python. The same rules apply for subtraction, multiplication, and division. Let’s quickly look at them.
Did you notice something? Every other operation (addition, subtraction, and multiplication) produced an integer as the output, but the result of division was a floating-point number. Take a note of this. Division always produces decimal numbers in Python. If there are no decimal points, it’ll just end the result with a “.0”, but it’ll still be a decimal (floating) number.
Special Math operations in Python
We’ve looked at the common operators. Let’s look at the special ones now.
You need to use the multiplication operator twice to do exponentiation. “**” is the operator you’re looking for.
So, instead of typing 2 * 2 * 2 * 2, which means 2 to the power of 4 (2 multiplied by itself four times), you can just type 2 ** 4 and you’d get the same result. If you had to multiply 2 by itself 20 times, just type 2 ** 20. You’d have saved a lot of time and space with this operator.
Yes, it works!
Did you see what happened? You got the floating-point value of the division as your first result and the remainder of 5 / 2 as your second result.
But what if you just need the quotient and not the complete result with the decimal point? You have an option for that as well!
It’s called the floor division operator. Write it with two forward slashes, like this: “//”.
Look at that. We just got 2 and not 2.5. 2 is the quotient of the operation 5 / 2. So, if you want the quotient and remainder separately, use the floor division to get the quotient of the operation and the modulus to get the remainder.
When you multiply 15 by 6, you’ll get 90. So, the quotient of 100 / 15 is 6 and the remainder is 10. We got the correct answer. It works!
Assignment operations
Python has something called assignment operations to make things easy for us. We’ve looked at one of them already. Remember the equal to, “=”, operator? You can use that operator to assign values to a variable.
Let’s quickly look at the rest. They are quite easy to understand.
There is the += operator.
a += 5 basically means a = a + 5. So, if you’d like to add a value to a variable and re-assign it back to the same variable, use this operator.
Similarly, you have -=, *=, /=, **=, %=, and //=.
Did you see something weird in the preceding operations? We started with integers, but the minute we performed a division operation, the rest of the results continued to be in floating point, regardless of the operation. We know why we got a floating point in the division operation. Division always results in a floating-point number. But why did it continue to be the case for the rest of the operations?
That’s because performing operations on a floating-point number will always result in a floating-point number, even if the other number is an integer.
What comes first?
Python, and any programming really, has something called precedence when it comes to order of executing mathematical operations. You must have learned about this in your math class too.
Remember the BODMAS rule? It basically says that anything within the brackets executes first and then comes the division, then multiplication, then addition, and finally subtraction.
Python does not have the exact rule, but it has something similar.
Order of execution happens from left to right.
Brackets hold the highest precedence.
Then comes the exponentiation operator **.
Then your multiplication (*), division (/), floor division (//), and modulus (%) operators. They hold the same level of precedence.
Finally, you have your addition (+) and subtraction (-) operators, which hold the same level of precedence as well.
Why don’t we put the rules to test?
Let’s take the following expression: 2 + 3 * 5.
Why is it 17? Since order of execution happens from left to right, shouldn’t 2 + 3 be executed first to result in 5, and shouldn’t the result (5) have been multiplied with 5 to result in 25 and not 17?
That’s where the precedence comes in. Even though order of execution is left to right, the operation with the higher precedence (in this case, multiplication) will be executed first, and then the result will be added to the first number (in our example).
Now we get a 25 because even though addition has lower precedence to multiplication, brackets hold the highest precedence, so they get executed first.
The preceding expression was done like this: (5) * 5 * (1 + 2) = 5 * 5 * 3 = 75.
When two operations hold the same precedence, the left to right rule is followed. Now that you know how precedence works in numbers, why don’t you write down different expressions and guess how they’d be executed in Python? Then you can execute them to verify your results.
Cool stuff with numbers
Python is a well that keeps on giving. You can do pretty much anything you want with numbers and manipulate them in any way you want. How? There’s a cool little tool called the Math module. Do you remember me telling you about Python add-ons that let you do cool stuff? This is one of them.
With this module, you can do pretty much everything you want with Python. You can find the power of a number, its square root, floor, ceiling, and so much more. Let’s look at some of the most important ones in this section. If you’d like to know more, a quick Google search will give you a list of all the operations you can do with the Math module. You have a bunch of pre-defined methods/functions that’ll help you achieve these things.
Let’s get started!
You can find the floor and ceiling numbers of decimal numbers. What is that? You can round off decimal numbers to their integer counterparts. But if you use the floor function, it’ll round the number to the lowest integer.
Open a new script file or clear out the one you’ve been using.
The preceding line of code basically tells our program that we’re importing the Math module to our file. Did you notice how we’ve written “math” with a small “m”? Make sure you do that. If you wrote it as “Math”, you’d get an error since Python is case sensitive. This applies for any pre-defined function or keyword you use in Python. You need to use them with no change to their spelling or case.
Floor and ceiling of a number
Look at that! Regardless of what the decimal point is, a floor operation will always result in the lowest integer, which is 5 in this case, and a ceil operation will always result in the highest integer, which is 6. Floor or ceil operations on integers have no effect on the number, and you’ll get the same number as the result.
Power and square root
Next, let’s look at powers. Remember how we used the “**” operator to find the power of a number? We have a Math operation that does something like that too.
Its syntax is math.pow(num,power).
The result is a floating-point number. Try working with decimal points and see what you get.
The result is a floating-point number again.
Factorial of a number
Do you know how to find the factorial of a number?
The factorial of 3 is 3 * 2 * 1, which is 6.
The factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120.
Yes, it works!
Sin, cos, tan, and more
If you know how sin, cos, tan, and log work, then you’ll find the next part interesting. If you don’t know these concepts, don’t worry. You can come back to this section once you’ve learned these concepts in your Math class.
You can verify the results with your scientific calculator, and you’ll find that the results are the same.
These are just some of the operations you can do with the Math module. There is at least a dozen more.
Check them out in the official Python documentation and play around with them, if you’d like: https://docs.python.org/3/library/math.html.
More numerical operations
Your fun with Math isn’t just isolated to the Math module. There are a bunch of stand-alone functions that do cool stuff as well. You won’t have to import the Math module to do these operations, but they’re just as powerful.
It works! –253 is the minimum number and 200.3452 is the maximum.
Working with random numbers
What if you didn’t want to come up with a number to use in your calculations? What if you wanted your computer to choose your number for you? Well, Python has got you covered.
Python has yet another module called the “random” module which comes with a bunch of cool functions that’ll help your computer choose a random number every time it’s run.
Let’s look at that now. You need to import the random module first. It’s “random” with a small “r”.
“random” is the name of the module, and “randrange” is the name of the function. I’ve given 11 in the second argument because the random module ignores the last number in the range. So, if I gave 10, then I’ll only get random numbers from 1 to 9. Since I wanted to include 10, I gave 11 as my second argument.
When you run the same lines of code multiple times, you’ll get different results than mine. Why don’t you try out and see for yourself?
Print the preceding code, and you’ll notice that you get one of the letters (including the exclamation point and space), every time you run the program.
Subsequent runs will give me random selections. Try and see!
Mini project – multiples of a number
In this mini project, I’ll teach you how to find the multiples of a number with a number method. So, if I want all the multiples of 3 until 100 displayed, for example, then this is what I’d do:
There’s yet another pre-defined method in Python called the “range” method. We’d usually only learn about this method when we learn about loops (in a later chapter), but I wanted to introduce it here, since technically, it is a number method.
- 1.
Let’s print the following line of code in the Python Shell:
- 2.
Alternatively, you can give the starting and ending numbers in a range as well, like this:
- 3.
Also, you can print the entire range using the “*” operator. No, don’t confuse it with the multiplication operator. This operator is used to print when something (in our case, the range) has more than one object (in our case, more than one number).
- 4.
Specify “*” before the variable so Python knows that you’re trying to print everything inside whatever is coming next. Alternatively, you can also write the same print statement like this:
- 5.
If I ran this:
- 6.
You can also skip numbers between ranges by using a third argument. If you give 2 as the third parameter, your program will print every 2nd number in the range. 3 as your 3rd parameter will print every 3rd number, 4 will print every 4th number, and so on.
You’ve printed out only the even numbers between 0 and 10. How great is that? You can skip any numbers you want with the third parameter.
- 7.
Let’s say we want to find the multiples of 3 from 1 to 100 and print them all out. So, that’s 3, 6, 9 until 99, am I right? You can do that in a single line of code. Would you like to try it yourself before you check the solution?
Whoa! Quite simple, wasn’t it?
We just gave the multiple as the first argument since it’s anyway going to be the first result – 3 * 1 = 3. Then we specified 101 as the second argument, so 100 would be included if it were a multiple. Finally, we gave 3 as the third argument again because we need to skip three numbers every time. And it worked!
Now, why don’t you try with different multiples and ranges and see how it works out for you?
Summary
In this chapter, we continued to look at numbers. We looked at how to use different operators available in Python to manipulate our numbers. We also looked at using the “Math” module and pre-defined functions to further play with our numbers. We finally looked at the “random” module, and we finished the chapter with a mini project as usual.
In the next chapter, let’s look at a very interesting concept in Python. We’ll be looking at using the Turtle module to draw graphics.