© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
A. ElumalaiIntroduction to Python for Kids https://doi.org/10.1007/978-1-4842-6812-4_5

5. Let’s Play with Our Numbers!

Aarthi Elumalai1  
(1)
Chennai, Tamil Nadu, India
 

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?

../images/505805_1_En_5_Chapter/505805_1_En_5_Figa_HTML.jpg

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.

Let’s look at addition first. You need to use the “+” symbol to add two numbers. If you want to add three numbers, use “+” twice. It’s just like how you add at your Math class.
num1 = 5
num2 = 7
add = num1 + num2
print(add)
When you run the preceding lines of code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
12
The answer is correct! Let’s make things more complicated, shall we?
num1 = 55.876
num2 = 100.54
#Add num1 and num2
add = num1 + num2
num3 = 1235.583
#Add the value in num3 to the current value in add
add = add + num3
print(add)
We created two numbers, “num1” and “num2”, added them, and stored the result in the variable “add”. Then, we created another variable “num3” and stored another number in it. We added the current value of “add” with “num3” and stored it back in “add” and printed the final value of “add”. Let’s see what we get:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
1391.999

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.

You need to use the “” symbol for subtraction, “/” for division, and “*” for multiplication. Unlike Math, using “x” or “X” for multiplication won’t work with programming languages.
num1 = 20
num2 = 10
#Addition
add = num1 + num2
print(add)
#Subtraction
sub = num1 - num2
print(sub)
#Multiplication
mul = num1 * num2
print(mul)
#Division
div = num1 / num2
print(div)
When your run the preceding lines of code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
30
10
200
2.0

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.

Let’s look at some examples.
exp = 2 ** 4
print(exp)
exp = 2 ** 20
print(exp)
exp = 5.5 ** 3
print(exp)
exp = 5.5 ** 3.5
print(exp)
As you can see in the preceding code, exponentiation works with floating-point numbers too. You can have floating-point numbers for both the number and the exponent (the power). Let’s look at the result to see if it works, shall we?
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
16
1048576
16.5
19.25

Yes, it works!

Now, let’s find our remainders. Use the modulus operator “%” instead of the division operator “/”, and you’ll get the remainder of the operation. Remember what happens when you divide a number by another number? You get a quotient and a remainder, am I right? Your modulus operator will do the same, but it’ll just return the remainder and not the quotient. If you want to find the quotient of the same operation, use the division operator with the same numbers.
#Division
div = 5 / 2
print(div)
#Remainder
r = 5 % 2
print(r)
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
2.5
1

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: “//”.

It’ll divide your numbers and return just the whole number, leaving out the decimal point. Let’s try the same with simple and complex examples.
floor = 5 // 2
print(floor)
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
2

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.

Let’s look at a more complex example to test if this really works:
#Division
div = 100 / 15
print(div)
#Quotient
q = 100 // 15
print(q)
#Remainder
r = 100 % 15
print(r)
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
6.666666666666667
6
10

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! ../images/505805_1_En_5_Chapter/505805_1_En_5_Figc_HTML.gif

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 //=.

Let’s look at examples of all of that now. Read the comments in the following lines of code to understand what each line of code does:
num = 5
#Add and re-assign 5
num += 5
#Ans -> 10
print(num)
#Subtract 5 from num
num -= 5
#Ans -> 5
print(num)
#Multiply the current value of num with 2
num *= 2
#Ans -> 10
print(num)
#Divide the value of num by 2
num /= 2
#Ans –> 5.0
print(num)
#Calculate num to the power 2 and re-assign it
num **= 2
#Ans –> 25.0
print(num)
#Find the quotient of num / 3
num //= 3
#Ans –> 8.0
print(num)
#Find the remainder of num / 3
num %= 3
#Ans –> 2.0
print(num)
When you run the preceding lines of code, you’ll get the following:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
10
5
10
5.0
25.0
8.0
2.0

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.

../images/505805_1_En_5_Chapter/505805_1_En_5_Figb_HTML.jpg

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.

The rules of precedence in Python are as follows:
  • 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.

Let’s run the preceding expression in our Python Shell and see what we get:
>>> 2 + 3 * 5
17

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).

But what happens if there’s a bracket?
>>> (2 + 3) * 5
25

Now we get a 25 because even though addition has lower precedence to multiplication, brackets hold the highest precedence, so they get executed first.

What if there are two brackets?
>>> (2 + 3) * 5 * (1 + 2)
75

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.

Before you use any of the pre-defined methods in the Math module, you need to import it into your script file first. You need to use the “import” keyword to do that.
import math

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

Okay, now that we’ve imported our Math module, let’s do our operations. The syntax to find the floor of a number is math.floor(num) where “num” is either the variable that holds the floating-point number or the number itself. The same goes for ceil.
import math
print(math.floor(5.6))
print(math.floor(5.3))
print(math.floor(5))
print(math.ceil(5.6))
print(math.ceil(5.3))
print(math.ceil(5))
When you run the preceding lines of code, you’ll get the following:
RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
5
5
5
6
6
5

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).

So, if you’d like to find the value of 5 to the power of 3 (5 * 5 * 5), then you’d do it like this:
import math
print(math.pow(5,3))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
125.0

The result is a floating-point number. Try working with decimal points and see what you get.

On the same vein, you can find the square root of numbers with the sqrt method. If 5 * 5 is 25, then the square root of 25 is 5. Let’s test!
import math
print(math.sqrt(25))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
5.0

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.

Are you seeing the pattern here? You wouldn’t have to laboriously calculate factorials anymore though. Python does that for you with the factorial method!
import math
print(math.factorial(5))
Run the preceding code and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
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 find the sin, cos, tan, and log of numbers with the relevant pre-defined methods. Before we start, I want to clarify something. The values/variables we give inside of the brackets () in any pre-defined method are called as arguments, and I’d be referring to them as such.
import math
print(math.sin(2))
print(math.cos(5))
print(math.tan(2))
print(math.log(10,2)) #The first argument is the number and the second is the base
Run the preceding code and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
0.9092974268256817
0.28366218546322625
-2.185039863261519
3.3219280948873626

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.

Would you like to find the minimum number among a list of numbers? Then use the “min” method, and give every number you want compared as the argument for that method, separated by commas. The same goes for “max”.
import math
print(min(-100,100,40,25.64,200.3452,-253))
print(max(-100,100,40,25.64,200.3452,-253))
I’ve given the same list of numbers for both min and max. Let’s look at the result:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
-253
200.3452

It works! –253 is the minimum number and 200.3452 is the maximum.

If you want to convert a negative number to a positive number in an operation, then use the “abs” method.
print(abs(-100))
The preceding code will result in this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
100

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”.

If you’d like a random number returned between the range you gave, use the randrange() function.
import random
print(random.randrange(1,11))

“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.

Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
10
When I ran it again, I got this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
2
The next time:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
7

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? ../images/505805_1_En_5_Chapter/505805_1_En_5_Figd_HTML.gif

We’ve just scratched the surface of the random module. There’s more where that came from. For example, you can ask your program to choose a letter from a word or phrase you specify, with the “choice” method.
import random
print(random.choice("Hello there!"))

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.

You can choose among a list of numbers as well. We’ll look at lists in detail in one of the later chapters, but for now, just understand that a list holds a list of a data, and in our examples, a list of numbers, and you should write the numbers within square brackets, separated by commas, like this:
import random
l = [1,3,5,7,9]
Let’s make our program randomly choose from this list now:
print(random.choice(l))
Run the preceding code; for the first run, I got this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
3

Subsequent runs will give me random selections. Try and see! ../images/505805_1_En_5_Chapter/505805_1_En_5_Fige_HTML.gif

There is the “random” method of the “random” module which returns a random floating-point number between 0 and 1.
import random
print(random.random())
When I ran the preceding code, I got this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
0.6386828169729072
Since randrange only returns integers within a range, I can use uniform to return floating-point numbers within a range. The only difference here is that this function considers both numbers of the range in its results.
import random
print(random.uniform(1,10))
When I ran the preceding code, I got this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
3.7563014275306283

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.

The range function, as the name implies, produces a range. You need to write it as range(num), where everything is written in small letters:
  1. 1.

    Let’s print the following line of code in the Python Shell:

     
>>> print(range(5))
Run the preceding code, and you’ll get this:
range(0, 5)
  1. 2.

    Alternatively, you can give the starting and ending numbers in a range as well, like this:

     
>>> print(range(1,10))
Run the preceding code, and you’ll get this:
range(1, 10)
  1. 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).

     
Let’s open our script and do the following:
r = range(1,10)
Now, the variable “r” contains the range. To print everything inside “r”, which is the list of numbers from 1 to 10, use “*”, like this:
print(*r)
  1. 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:

     
print(*range(1,10))
Run either of those statements, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
1 2 3 4 5 6 7 8 9
Yup, it works!
  1. 5.

    If I ran this:

     
print(*range(10))
I’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
0 1 2 3 4 5 6 7 8 9
As you can see, if you don’t give a starting range, then it prints from 0 to the number before the ending range.
  1. 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.

     
print(*range(0,10,2))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
0 2 4 6 8

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.

Now that we know all of this, can you guess how we can apply this to solve our problem? So, we need to find the multiples of the given number within the given range, and we know that we’re going to use the range() function to do that.
  1. 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?

     
Tried? Okay, let’s look at the solution now!
print(*range(3,101,3))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32 umbers.py
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99

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! ../images/505805_1_En_5_Chapter/505805_1_En_5_Figf_HTML.gif

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.20.56