Introduction
Obviously working with numbers in programming is important. Python as excellent mathematical capabilities, and there are tons of additional libraries available to extend Python’s built in functionality for even the most advanced calculations. Of course, the basics are important too, and numbers and some basic calculations come into play when controlling the flow of programs and making selections. That’s why knowing your way around working with numbers in Python is especially important.
As previously stated in the last guide, there are two basic types of number variables that you will encounter. Whole numbers, or floats
.
Integers
Since you don’t specify variable types when you create them in Python, it will just assume that it is working only with integers unless a decimal point is present. This works well most of the time, and provides clean output. There’s one pretty obvious exception. Take a look at this division problem.
>>> 10/5 2.0
Notice how there’s a decimal point even though the problem divides evenly? The integers were converted into a float. In Python 2 and many other programming languages, the language would ignore anything after the last whole number. Check out this Python 2 example.
>>> 15 / 4 3
Python 2 just drops everything after the last whole number. It’s pretty easy to make mistakes this way. That’s way Python 3 decided that every time division was performed, it would automatically convert to float.
Floats
Any number with a decimal place is considered a float in Python. Since Python assumes that any number is going to be an integer unless there’s a decimal place present, you have to add a decimal place, if you want to tell Python that you’re working with a float.
>>> 20 + 10.5 30.5
Even if there is only one decimal place present, Python will convert the output to a float to ensure that the results are kept as accurate as possible. Generally speaking, if you aren’t sure that your calculations are going to result in whole numbers, throw a decimal place in to ensure that you receive accurate results.
Math
Python supports all of the basic math operations without adding anything. In the previous guides, you’ve used many of them. The table below provides a breakdown of each one.
Math Operators | |
---|---|
+ | Addition | – | Subtraction |
* | Multiplication |
/ | Division |
** | Exponents |
You’ve already tried using some of them, but try some more. String together as many as you can. Python’s math operators follow the same order of operations as regular mathematics. That includes the use of parenthesis.
>>> 25 * 3 / (5 ** 2 - 20) 15.0
You can see a couple of things going on there, one of which is the conversion from an integer to a float during division. The parenthesis also come into play to force order of operations. Look what happens when they are removed.
>>> 25 * 3 / 5 ** 2 - 20 -17.0
Since it’s not possible to type a numerator above a denominator, Python must be told that the -20
is part of the denominator. Otherwise, it just prioritizes the subtraction after the exponent, multiplication and division.
Changing Variable Values
Instances are going to arise when you want to modify the value of a variable mathematically. In fact, its a very important thing to be able to do. The most straightforward way to go about this is to set the variable equal to itself being modified by an expression.
a = a + 5
Python will recall the current value of a
and add five to it. Then, it will reassign the newly computed value to a
. This will work with other mathematical operations as well.
a = (a ** 2) / 5
You can even throw in the values of other variables as well.
a = 2 b = 5 a = (a ** a) / b
You can have an entire expression made up only of variables, as long as they have been assigned values.
Most of the time, you’ll only be performing a single operation to modify a variable. Using an entire expression like the example above tends to be a rarer occurrence. Since writing a = a + 1
is tends to be both redundant and tedious, Python gives you a shortened way. Instead of writing, a = a + 1
, you can write a += 1
. These shorthand assignment operators exist for all of the other basic math operations as well.
a += 1 a -= 5 a *= 3 a /= 4 a **= 2
They all work in roughly the same way. For example, a *= 3
is the same as a = a * 3
.
The Math Library
It’d be pretty hard to talk about numbers in Python and doing math without talking about the math library. The Python math library contains many of the tools that you’d need to do more complex mathematical operations. A very common example of a reason to use the math library is finding the square root of a number. So, it’s probably a good idea to try that out.
In order to get access to the math library, you have to import it. Importing a library only involves adding a single import line to your code. If you’re using a Python file, it’s best to add imports first, right below the shebang line.
import math
Now that the math library is imported, you can use it. The square root functionality is called sqrt()
. To use it, you need to place the number or expression that you want to take the square root of in the parenthesis.
import math math.sqrt(10 + 15)
You have to add math.
in from to tell Python that that’s where that functionality is coming from.
There are a ton of other things that you can do with the math library. If you’d like to read about them, you can find the official documentation here.
Closing
Familiarize yourself with the different functionality that Python provides for working with numbers and the way that it handles integers and floats. Practice running different mathematical equations and working with the assignment operators for changing the values of variables. If you want to go more in-depth with math, explore the math library and the functions that it provides.
Exercises
- Divide 23 by 2 and print the result.
- Add 12.5 and 10. Is the result an integer or a float?
- Do the following in a single line of code. Raise four to the second power and multiply the result by itself. Subtract 64. Then divide the entire thing by 8 and print the result. Be sure that
Python if following the proper order of operations. - Create a variable and set it equal to a number. Then, take that number and set it equal to itself raised to the third power. Print the new value.
- Create a variable called
a
. Seta
equal to a number. Now, seta
equal to(a ** a / a + a)
. Print the new value ofa
. - Create a variable called
a
, and set it equal to a number. Do the same with a variable calledb
. Seta
equal to itself divided byb
and print
the result. - Create a variable called
a
. Use an assignment operator to set it equal to itself plus 10. Print. - Create a variable called
a
. Use an assignment operator to set it equal to itself divided by 3. Print. - Create a variable called
a
. Use an assignment operator to set it equal to itself raised to the fourth power. Print. - Create a variable called
a
, and set it equal to a number. Do the same with a variable calledb
. Use an assignment operator to setb
equal to the
difference of itself anda
. - Import the math library and use it to find the square root of 81.
- Import the math library and use it to find the square root of
512/2
. - Create two variables
a
andb
and set them each equal to a multiple of 4 and 5 respectively.c
squared is equal to the sum ofa
squared andb
squared. Find and print the value ofc
.
Table of Contents
- Python Introduction and Installation Guide
- Python Files and the Interpreter
- Experimenting With Numbers and Text In Python
- Python Variables
- Working With Number Variables In Python
- Python String Basics
- Advanced Python Strings
- Python Comments
- Python Lists
- Python List Methods
- Python Multidimensional Lists
- Python Tuples
- Python Boolean Operators
- Python If Statements
- Python While Loops
- Python For Loops
- Python Dictionaries
- Python Advanced Dictionaries
- Python Functions