# Python as a Calculator

Now that you are all set up, you can begin with the very first interesting topic. Python is an incredibly powerful calculator. By leveraging the `math`

library, `numpy`

, and `scipy`

, Python typically outperforms pre-programmed calculators. In later chapters, you will learn how to use the `numpy`

and `scipy`

libraries. For now, we'll introduce the calculator tools that most people use daily.

**Addition**, **subtraction**, **multiplication**, **division**, and **exponentiation** are core operations. In computer science, the `modulus`

operator and **integer division** are equally essential as well, so we'll cover them here.

The `modulus`

operator is the remainder in mathematical division. **Modular arithmetic** is also called **clock arithmetic**. For instance, in `mod5`

which is a modulus of 5, we count 0,1,2,3,4,0,1,2,3,4,0,1... This goes in a circle, like the hands on a clock.

The difference between division and integer division depends on the language. When dividing the integer 9 by the integer 4, some languages return 2; others return 2.25. In your case, Python will return 2.25.

There are many advantages to using Python as your calculator of choice. The first is that you are not limited to using programs that others have written. You can write a program to determine the greatest common divisor or the Euclidean distance between two points.

Other advantages include reliability, precision, and speed. Python generally prints out more decimal places than most calculators, and it always does what you command it to do.

We'll cover a small sample of what Python can calculate. Complex numbers are previewed as a Python type. Great `math`

libraries such as `Turtle`

, which creates polygons and circles with ease, may be explored in your own time and are mentioned in *Chapter 6*, *The Standard Library*. The depth of math required for data analysis and machine learning starts with the foundations laid here.

Note

In this book, copy everything that follows `>>>`

in a cell in your Jupyter Notebook; that is, you exclude `>>>`

. To run code, make sure the cell is highlighted, then press *Shift* + *Enter*. You may also press the `Run`

button at the top of the Notebook, but this takes more time. Start thinking like a developer and use keystrokes instead.

## Standard Math Operations

You can have a look at the standard math operations and their symbols that we will be using while coding. The following table covers these:

Note

The `**`

symbol is not universally for exponentiation, but it should be. By definition, exponentiation is repeated multiplication. Using the `*`

symbol twice is representative of repeated multiplication. It's terse, fast, and efficient. Other programming languages require functions to exponentiate.

Python provides an optional method from the `math`

library, `math.pow()`

, but `**`

is cleaner and easier to use.

## Basic Math Operations

We can perform addition on two numbers using the `+`

operator. The following example shows the addition of 5 and 2:

- Here, we are using the addition operator,
`+`

in the code:5 + 2

You should get the following output:

7

We can perform addition on two numbers using the

`+`

operator. The following example shows the subtraction of`5`

and`2`

. - Using the subtraction operator in the code, we can perform subtraction on two numbers:
5 - 2

You should get the following output:

3

The following example shows the multiplication of 5 by 2.

- Using the
`*`

multiplication operator to multiply the two numbers is done as follows:5 * 2

You should get the following output:

10

- Now, use the
`/`

division operator and observe the output:5 / 2

You should get the following output:

2.5

When dividing two numbers, Python will always return a decimal.

- Now the same division can be done using the
`//`

operator, which is called integer division. Observe the change in the output:5 // 2

You should get the following output:

2

The result of the integer division is the integer before the decimal point.

- Now, using the
`**`

exponential operator, we can perform exponentiation:5 ** 2

You should get the following output:

25

The next example shows how to use the modulus operator.

- Finally, use the modulus operator in the code and observe the output:
5 % 2

You should get the following output:

1

The modulus operator is performed using the

`%`

operator, as shown in step 7. It returns the remainder when the first number is divided by the second.

In the aforementioned examples, you have used the different math operators and performed operations with them in a Jupyter Notebook. Next, you move on to the order of operations in Python.

## Order of Operations

Parentheses are meaningful in Python. When it comes to computation, Python always computes what is in parentheses first.

The Python language follows the same order of operations as in the math world. You may remember the acronym PEMDAS: parentheses first, exponentiation second, multiplication/division third, and addition/subtraction fourth.

Consider the following expression:`5 + 2 * -3`

The first thing to note is that the negative sign and subtraction sign are the same in Python. Let's have a look at the following example:

- Python will first multiply
`2`

and`–3`

, and then add`5`

:5 + 2 * -3

You should get the following output:

–1

- If parentheses are placed around the
`5`

and`2`

, we obtain a different result:(5 + 2) * -3

You should get the following output:

–21

If ever in doubt, use parentheses. Parentheses are very helpful for complex expressions, and extra parentheses do not affect code.

In the following exercise, we are going to dive into Python code and work with math operations.

## Exercise 1: Getting to Know the Order of Operations

The goal of this exercise is to work with the primary math operations in Python and understand their order of execution. This exercise can be performed on the Python terminal:

- Subtract
`5`

to the 3rd power, which is 53, from`100`

and divide the result by`5`

:(100 - 5 ** 3) / 5

You should get the following output:

–5.0

- Add
`6`

to the remainder of`15`

divided`4`

:6 + 15 % 4

You should get the following output:

9

- Add
`2`

to the 2nd power, which is 22, to the integer division of`24`

and`4`

:2 ** 2 + 24 // 4

You should get the following output:

10

In this quick exercise, you have used Python to perform basic math using the order of operations. As you can see, Python is an excellent calculator. You will use Python often as a calculator in your career as a developer.

## Spacing in Python

You may have wondered about spaces in between numbers and symbols. In Python, spaces after a number or symbol do not carry any meaning. So, `5**3`

and `5 ** 3`

both result in `125`

.

Spaces are meant to enhance readability. Although there is no correct way to space code, spaces are generally encouraged between operands and operators. Thus, `5 ** 3`

is preferable.

Trying to follow certain conventions is perfectly acceptable. If you develop good habits early on, it will make the reading and debugging of code easier later.

## Number Types: Integers and Floats

Now you will address the difference between an integer and a float. Consider 8 and 8.0. You know that 8 and 8.0 are equivalent mathematically. They both represent the same number, but they are different types. 8 is an integer, and 8.0 is a decimal or float.

An integer in Python is classified as a type of `int`

, short for integer. Integers include all positive and negative whole numbers, including 0. Examples of integers include 3, -2, 47, and 10000.

Floats, by contrast, are Python types represented as decimals. All rational numbers expressed as fractions can be represented as floats. Samples of floats include 3.0, -2.0, 47.45, and 200.001.

Note

We are only covering text and numeric types in this chapter. Other types will be discussed in subsequent chapters.

Python types can be obtained explicitly using the `type()`

keyword, as you will see in the following exercise.

## Exercise 2: Integer and Float Types

The goal of this exercise is to determine types and then change those types in our Python code. This can be performed in the Jupyter Notebook:

- Begin by explicitly determining the type of
`6`

using the following code:type(6)

You should get the following output:

int

- Now, enter
`type(6.0)`

in the next cell of your notebook:type(6.0)

You should get the following output:

float

- Now, add
`5`

to`3.14`

. Infer the type of their sum:5 + 3.14

You should get the following output:

8.14

It's clear from the output that combining an

`int`

and a`float`

gives us a`float`

. This makes sense. If Python returned 8, you would lose information. When possible, Python converts types to preserve information.You can, however, change types by using the

`type`

keyword. - Now, convert
`7.999999999`

to an`int`

:int(7.999999999)

You should get the following output:

7

- Convert
`6`

to a`float`

:float(6)

You should get the following output:

6.0

In this exercise, you determined types by using the `type()`

keyword, and you changed types between integers and floats. As a developer, you will need to use your knowledge of variable types more often than you might expect. It's not uncommon to be unsure of a type when dealing with hundreds of variables simultaneously, or when editing other people's code.

Note

Type changing will be revisited again in this chapter, referred to as **casting**.

## Complex Number Types

Python includes complex numbers as an official type. Complex numbers arise when taking the square roots of negative numbers. There is no real number whose square root is -9, so we say that it equals 3i. Another example of a complex number is 2i + 3. Python uses `j`

instead of `i`

.

You can take a look at the following code snippet to learn how to work with complex number types.

Divide `2 + 3j`

by `1 - 5j`

, enclosing both operations within parentheses:

(2 + 3j) / (1 - 5j)

You should get the following output:

–0.5+0.5j

For more information on complex numbers, check out https://docs.python.org/3.7/library/cmath.html.

## Errors in Python

In programming, errors are not to be feared; errors are to be welcomed. Errors are common not only for beginners but for all developers. You will learn skills to handle errors in *Chapter 4*, *Extending Python, Files, Errors, and Graphs*. For now, if you get an error, just go back and try again. Python errors in Jupyter Notebooks won't crash your computer or cause any serious problems but they will just stop running the Python code.

## Variables

In Python, variables are memory slots that can store elements of any type. The name variable is meant to be suggestive, as the idea behind a variable is that the value can vary throughout a given program.

## Variable Assignment

In Python, variables are introduced the same way as in math, by using the equals sign. In most programming languages, however, order matters; that is, x = 3.14 means that the value 3.14 gets assigned to x. However, 3.14 = x will produce an error because it's impossible to assign a variable to a number. In the following exercise, we will implement this concept in code to give you a better understanding of it.

## Exercise 3: Assigning Variables

The goal of this exercise is to assign values to variables. Variables can be assigned any value, as you will see in this exercise. This exercise can be performed in the Jupyter Notebook:

- Set
`x`

as equal to the number`2`

:x = 2

In the first step, we assigned the value

`2`

to the`x`

variable. - Add
`1`

to the variable`x`

:x + 1

You should get the following output:

3

Once we add

`1`

to`x`

, we get the output of`3`

, because the variable has`1`

added to it. - Change
`x`

to`3.0`

and add`1`

to`x`

:x = 3.0 x + 1

You should get the following output:

4.0

In this step, we change the value of

`x`

to`4.0`

, and as in the previous 2 steps, we will be adding`1`

to the`x`

variable.

By the end of this quick exercise, you may have noticed that in programming, you can assign a variable in terms of its previous value. This is a powerful tool, and many developers use it quite often. Furthermore, the type of `x`

has changed. `x`

started as an `int`

, but now `x`

= `3.0`

which is a `float`

. This is allowed in Python because Python is dynamically typed.

## Changing Types

In some languages, it's not possible for a variable to change types. This means that if the `y`

variable is an integer, then `y`

must always be an integer. Python, however, is dynamically typed, as we saw in *Exercise 3*, *Assigning Variables* and as illustrated in the following example:

`y`

starts as an integer:y = 10

`y`

becomes a float:y = y – 10.0

- Check the type of
`y`

:type(y)

You should get the following output:

float

In the next topic, you will be looking at reassigning variables in terms of themselves.

## Reassigning Variables in Terms of Themselves

It's common in programming to add `1`

to a variable; for instance, `x = x + 1`

. The shorthand for this is to use `+=`

as in the following example:

x += 1

So, if `x`

was `6`

, `x`

is now `7`

. The `+=`

operator adds the number on the right to the variable and sets the variable equal to the new number.

## Activity 1: Assigning Values to Variables

In this activity, you will assign a number to the `x`

variable, increment the number, and perform additional operations.

By completing this activity, you will learn how to perform multiple mathematical operations using Python. This activity can be performed in the Jupyter Notebook.

The steps are as follows:

- First, set
`14`

to the`x`

variable. - Now, add
`1`

to`x`

. - Finally, divide
`x`

by`5`

and square it.You should get the following output:

9.0

Note

The solution for this activity can be found via this link.

## Variable Names

To avoid confusion, it's recommended to use variable names that make sense to readers. Instead of using `x`

, the variable may be `income`

or `age`

. Although `x`

is shorter, someone else reading the code might not understand what `x`

is referring to. Try to use variable names that are indicative of the meaning.

There are some restrictions when naming variables. For instance, variables cannot start with numbers, most special characters, keywords, nor built-in types. Variables also can't contain spaces between letters.

According to Python conventions, it's best to use lowercase letters and to avoid special characters altogether as they will often cause errors.

Python keywords are reserved in the language. They have special meanings. We will go over most of these keywords later.

Running the following two lines always shows a current list of Python keywords:

import keyword print(keyword.kwlist)

You should get the following output:

Note

If you use any of the preceding keywords as variable names, Python will throw an error.

## Exercise 4: Variable Names

The goal of this exercise is to learn standard ways to name variables by considering good and bad practices. This exercise can be performed in Jupyter:

- Create a variable called
`1st_number`

and assign it a value of`1`

:1st_number = 1

You should get the following output:

You'll get the error mentioned in the preceding screenshot because you cannot begin a variable with a number.

- Now, let's try using letters to begin a variable:
first_number = 1

- Now, use special characters in a variable name, as in the following code:
my_$ = 1000.00

You should get the following output:

You get the error mentioned in Figure 1.4 because you cannot include a variable with a special character.

- Now, use letters again instead of special characters for the variable name:
my_money = 1000.00

In this exercise, you have learned to use underscores to separate words when naming variables, and not to start variables' names with numbers nor include any symbols. In Python, you will quickly get used to these conventions.

## Multiple Variables

Most programs contain multiple variables. The same rules apply as when working with single variables. You will practice working with multiple variables in the following exercise.

## Exercise 5: Multiple Variables in Python

In this exercise, you will perform mathematical operations using more than one variable. This exercise can be performed in the Jupyter Notebook:

- Assign
`5`

to`x`

and`2`

to`y`

:x = 5 y = 2

- Add
`x`

to`x`

and subtract`y`

to the second power:x + x - y ** 2

You should get the following output:

6

Python has a lot of cool shortcuts, and multiple variable assignment is one of them. Here's the Pythonic way of declaring two variables.

Note

Pythonic is a term used to describe code written in the optimum readable format. This will be covered in

*Chapter 7*,*Becoming Pythonic*. - Assign
`8`

to`x`

and`5`

to`y`

in one line:x, y = 8, 5

- Find the integer division of x and y:
x // y

You should get the following output:

1

In this exercise, you practiced working with multiple variables, and you even learned the Pythonic way to assign values to multiple variables in one line. It's rare to only work with one variable in practice.

## Comments

Comments are extra blocks of code that do not run. They are meant to clarify code for readers. In Python, any text following the `#`

symbol on a single line is a comment. Comments followed by the `#`

symbol may be inline or above the text.

Note

Consistent use of comments will make reviewing and debugging code much easier. It's strongly advisable to practice this from here on out.

## Exercise 6: Comments in Python

In this exercise, you will learn two different ways to display comments in Python. This exercise can be performed in the Jupyter Notebook:

- Write a comment that states
`This is a comment`

:# This is a comment

When you execute this cell, nothing should happen.

- Set the
`pi`

variable as equal to`3.14`

. Add a comment above the line stating what you did:# Set the variable pi equal to 3.14 pi = 3.14

Adding the comment clarifies what follows.

- Now, try setting the
`pi`

variable as equal to`3.14`

again, but add the comment stating what you did on the same line:pi = 3.14 # Set the variable pi equal to 3.14

Although it's less common to provide comments on the same line of code, it's acceptable and often appropriate.

You should get the following output from the Jupyter notebook:

In this exercise, you have learned how to write comments in Python. As a developer, writing comments is essential to make your code legible to others.

## Docstrings

Docstrings, short for document strings, state what a given document, such as a program, a function, or a class, actually does. The primary difference in syntax between a docstring and a comment is that docstrings are intended to be written over multiple lines, which can be accomplished with triple quotes `"""`

. They also introduce a given document, so they are placed at the top.

Here is an example of a docstring:

""" This document will explore why comments are particularly useful when writing and reading code. """

When you execute this cell, nothing really happens. Docstrings, like comments, are designed as information for developers reading and writing code; they have nothing to do with the output of code.

## Activity 2: Finding a Solution Using the Pythagorean Theorem in Python

In this activity, you will determine the Pythagorean distance between three points. You will utilize a docstring and comments to clarify the process.

In this activity, you need to assign numbers to the `x`

, `y`

, and `z`

variables, square the variables, and take the square root to obtain the distance, while providing comments along the way and a docstring to introduce the sequence of steps. To complete this activity, you'll utilize multiple variables, comments, and docstrings to determine the Pythagorean distance between three points.

The steps are as follows:

- Write a docstring that describes what is going to happen.
- Set
`x`

,`y`

, and`z`

as equal to`2`

,`3`

, and`4`

. - Determine the Pythagorean distance between
`x`

,`y`

, and`z`

. - Include comments to clarify each line of code.
You should get the following output:

5.385164807134504

Note

The solution for this activity can be found via this link.

So far, in this chapter, you have used Python as a basic calculator, along with the order of operations. You examined the difference between `int`

and `float`

values and learned how to convert between them. You can implement variable assignment and reassign variables to make programs run more smoothly. You also utilized comments to make code more readable and learned how to identify syntax errors. In addition, you learned a couple of cool Python shortcuts, including assigning multiple variables to one line. As an added bonus, you explored Python's complex number types.

Next, you'll explore Python's other main type, strings.