Back to Course

Introduction to Python

0% Complete
0/0 Steps
  1. Python: Basics
    14Topics
    |
    15 Quizzes
  2. Python: Control Flow
    12Topics
    |
    12 Quizzes
  3. Python: Errors
    5Topics
    |
    5 Quizzes
Lesson 1, Topic 7
In Progress

Python: Arithmetics

Yasin Cakal 4 Oct 2021
Lesson Progress
0% Complete

Computers are unmatched in their ability to perform calculations. The term “compute” is derived from their historical association with providing solutions to mathematical problems. With +, -, *, and /, Python performs addition, subtraction, multiplication, and division.

x = 8
y = 4

print(x + y)
print(y - x)
print(x * y)
print(x / y)

Output:

12
-4
32
2.0

Please take note that when we divide, the result contains a decimal place. This is because before performing division, Python converts all ints to floats. This conversion did not occur in earlier versions of Python (2.7 and earlier), and integer division was always rounded down to the nearest integer.

Division can generate a unique error called ZeroDivisionError. Python will throw this error if it tries to divide by zero.

Python’s mathematical operations are performed in the standard mathematical order. Remember PEMDAS? Here is how it works:

  • P = Parentheses first
  • E = Exponents including Powers and Square Roots
  • MD = Multiplication and Division, Left to Right
  • AS = Addition and Subtraction, Left to Right
%d bloggers like this: