Using Basic Math Operators in Python


Math is an important part of coding. It is used to keep track of player scores in games, to calculate mortgage payments, and determine how long it will take to download a file.

In this blog post, we will be discussing the different math operators available in the Python programming language. After reading this post, you should have a basic understanding of how to use the +, -, *, /, //, %, and ** operators in your Python code.

The “+” Operator

The “+” operator is used for addition. For example, if we want to calculate the total of 5 plus 2, we would write “5 + 2” in our code. The output of this code would be 7.

a, b = 5, 2 # a = 5, b = 2 # Using the "+" operator: print(a + b) #Output: 7 # Using the "in-place" "+=" operator to add and assign: a += b # a = 7 (equivalent to a = a + b) import operator # contains 2 argument arithmetic functions for the examples print(operator.add(a, b)) #Output: 7 # The "+=" operator is equivalent to: a = operator.iadd(a, b) # a = 7
Code language: Python (python)

Note that you can also use the + operator to join strings, lists, and tuples:

"first string " + "second string" # = 'first string second string' [1, 2, 3] + [4, 5, 6] # = [1, 2, 3, 4, 5, 6]
Code language: Python (python)

The “-” Operator

The “-” operator is used for subtraction. For example, if we want to calculate 5 minus 2, we would write “5 – 2” in our code. The output of this code would be 3.

a, b = 2, 5 # a = 2, b = 5 # Using the "-" operator: b - a # = 3 import operator # contains 2 argument arithmetic functions print(operator.sub(b, a)) #Output: 3
Code language: Python (python)

The “*” Operator

The “*” operator is used for multiplication. For example, if we want to calculate 5 multiplied by 2, we would write “5 * 2” in our code. The output of this code would be 10.

a, b = 5, 2 # a = 5, b = 2 a * b # = 10 import operator operator.mul(a, b) # = 10
Code language: Python (python)

Note: The * operator is also used for repeated concatenation of strings, lists, and tuples:

4 * 'xy' # = 'xyxyxyxy' 4 * ('x', 'y') # = ('x', 'y', 'x', 'y','x', 'y', 'x', 'y')
Code language: PHP (php)

The “/” Operator

The “/” operator is used for division. For example, if we want to calculate 5 divided by 2, we would write “5 / 2” in our code. The output of this division code would be 2.5 because division always outputs a decimal answer unless both numbers being divided are divisible by each other with no remainder (for example 10 / 5 = 2).

What if you want float division:

Recommended:

a, b, c, d, e = 3, 2, 2.0, -3, 1 from __future__ import division # applies Python 3 style division to the entire module a / b # = 1.5 a // b # = 1 Okay (if you don't want to apply to the whole module): a / (b * 1.0) # = 1.5 1.0 * a / b # = 1.5 a / b * 1.0 # = 1.0 (careful with order of operations) #from operator import truediv truediv(a, b) # = 1.5 # Not recommended (may raise TypeError, eg if argument is complex): float(a) / b # = 1.5 a / float(b) # = 1.5
Code language: Python (python)

In Python 3, the / operator does “true” division, no matter what type the numbers are. The / operator divides by the floor and keeps the type.

a / b # = 1.5 e / b # = 5.0 a // b # = 1 a // c # = 1.0 import operator # the operator module provides 2-argument arithmetic functions operator.truediv(a, b) # = 1.5 operator.floordiv(a, b) # = 1 operator.floordiv(a, c) # = 1.0
Code language: Python (python)

The “//” Operator

The “//” operator is similar to the “/” operator but it rounds the answer down to the nearest whole number rather than returning a decimal answer. So if we use the same numbers from before and type “5 // 2”, the output will just be 2 without the “.5”.

a, b, c, = 5, 2, 2.0 a // b # = 2 a // c # = 2.0
Code language: JavaScript (javascript)

Useful tip: You can use the “//” operator when working with large numbers that you don’t need an exact answer for and you want your program to run faster too!

Example: 1000000000 // 3 = 333333333 (it’s about 33% faster than typing 1000000000 / 3)

Another useful tip: The “%” or modulo operator gives you the remainder after division so “5 % 2 = 1”. Try it out in your IDLE shell!

The “**” Operator

The “**” or double asterisk operator is used for exponentiation which means raising a number to a power. In simpler terms, it multiplies a number by itself X amount of times where X is whatever number you put after the double asterisks.

So if we want to know what 5 squared (or five to the power of two) equals we can just write “5 ** 2”. The output will equal 25 because five multiplied by itself two times equals 25 (22 = 4; 23 = 8; 24 = 16; 25 = 32…etc).

a, b = 5, 2 (a ** b) # = 25 pow(a, b) # = 25 import math math.pow(a, b) # = 25.0 (always float; does not allow complex results) import operator operator.pow(a, b) # = 25 Another difference between the built-in pow and math.pow is that the built-in pow can accept three arguments: a, b, c = 2, 3, 2 pow(2, 3, 2) # 0, calculates (2 ** 3) % 2, but as per Python docs, # does so more efficientl
Code language: Python (python)

Remember: If you don’t put anything after the double asterisks then it will raise a number to the power of two because that’s just how exponentiation works by default! But feel free to experiment with other powers 🙂

Modulus

In Python, the % operator is used to calculate modulus, just like in many other programming languages.

3 % 4 # 3 15 % 3 # 0 6 % 5 # 1
Code language: PHP (php)

Or by using the operator module:

import operator operator.mod(3 , 4) # 3 operator.mod(15 , 3) # 0 operator.mod(6 , 5) # 1 # You can also use negative numbers. -9 % 7 # 5 9 % -7 # -5 -9 % -7 # -2 #If you need to find the result of integer division and modulus, you can use the divmod function as a shortcut: quotient, remainder = divmod(9, 4) # quotient = 2, remainder = 1 as 4 * 2 + 1 == 9
Code language: Python (python)

Special functions

The function math.sqrt(x) calculates the square root of x

import math import cmath x = 4 math.sqrt(x) # = 2.0 (always float; does not allow complex results) cmath.sqrt(x) # = (2+0j) (always complex)
Code language: PHP (php)

To find other roots, like the root of a cube, raise the number to the degree of the root’s reciprocal. Any of the exponential functions or operators could be used to do this.

import math x = 8 math.pow(x, 1/3) # evaluates to 2.0 x**(1/3) # evaluates to 2.0 The function math.exp(x) computes e ** x. math.exp(0) # 1.0 math.exp(1) # 2.718281828459045 (e) The function math.expm1(x) computes e ** x - 1. When x is small, this gives significantly better precision than math.exp(x) - 1. math.expm1(0) # 0.0 math.exp(1e-6) - 1 # 1.0000004999621837e-06 math.expm1(1e-6) # 1.0000005000001665e-06 # exact result # 1.000000500000166666708333341666...
Code language: Python (python)

Inplace Operations

It is common within applications to need to have code like this:

a = a + 1 or a = a * 2

There is an effective shortcut for these in-place operations:

a += 1 # and a *= 2
Code language: PHP (php)

Any mathematic operator can be used before the ‘=’ character to make an in-place operation:

  • -= decrement the variable in place
  • += increment the variable in place
  • *= multiply the variable in place
  • /= divide the variable in place
  • //= floor divide the variable in place # Python 3
  • %= return the modulus of the variable in place
  • **= raise to a power in place

Other in-place operators exist for the bitwise operators (^, | etc)

Math operators are very important when coding and there are many more applications for them that weren’t covered in this blog post so feel free to experiment on your own time! And as always, happy coding!

Conclusion:

By understanding how these operators work, you lay the foundation needed for solving more complex problems later on. Experiment with different inputs and review how the outputs change based on what values are inputted into each operator equation. With time and practice, utilizing these operators will become second nature!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts