Launching Python
The way you start the Python interpreter depends on the system you have. In Linux, macOS, or Windows with the Windows Subsystem for Linux, you just type “python” or “python3” into the terminal command prompt.
Arithmetic Operations
When you launch the Python interpreter, you’ll find yourself at the Python prompt. The arithmetic operators are familiar if you’ve ever used a calculator before.
Addition is simple:
The interpreter will of course return “4.”
Subtraction is the same.
You can also multiply. This uses the * symbol.
Division uses the / operator. In Python 3, this will return the remainder as a decimal fraction:
Exponents use the ** operator:
More Advanced Math
Sometimes, you want to perform more advanced calculations than Python’s built-in arithmetic operations offer. As with other programming languages, Python uses libraries to extend its functionality, and math is no exception. As part of its standard library, Python includes the Math library.
To use it, simply type this in the interpreter prompt:
The math library comes with trigonometric functions as well as information about numbers. It also includes an approximation of pi. Let’s use this to prove that you should always order a bigger pizza, because you get more pizza for your money as the area increases with the square of the radius with a round pizza. Remember, the formula for the area of a circle is pi times the radius (half of the diameter) of the circle squared.
For example, here’s the area of an 8-inch pizza with Python:
The answer, rounded off, is 50.27 square inches. And for a 16-inch pizza:
A 16-inch pizza has an area of 201.06 square inches. That’s nearly four times as much pizza than the 8-inch pizza!
A Handy Calculator for the Command-Line
Having the calculator running in a window in the background makes it easy to perform simple calculations. It’s faster to use Python than to fumble with a graphical calculator. If you don’t want to use the terminal or your device doesn’t have one, you can use a web-based Python interpreter instead.