How To Do Math in Python 3 with Operators?

Published on Aug. 22, 2023, 12:15 p.m.

To do math operations in Python 3 with operators, you can use the basic arithmetic operators such as + for addition, - for subtraction, * for multiplication, / for division, and % for modulus.

Here are some examples of how to use these operators:

# addition
a = 5
b = 3
c = a + b
print(c)  # output: 8

# subtraction
a = 10
b = 5
c = a - b
print(c)  # output: 5

# multiplication
a = 3
b = 4
c = a * b
print(c)  # output: 12

# division
a = 10
b = 3
c = a / b
print(c)  # output: 3.3333333333333335

# modulus
a = 10
b = 3
c = a % b
print(c)  # output: 1

You can also use parentheses to group operations and control the order of evaluation, and you can use the power operator ** to raise a number to a power. For example:

# grouping and power
a = 2
b = 3
c = (a + b) ** 2
print(c)  # output: 25

In this example, we first add a and b, then square the result using parentheses and the power operator.

Tags: