|

# How To Use Numbers In Python

You might have heard that programming requires lots of Math. You can actually get by doing a lot of programming without intense math, as long as you have basic arithmetic skills. For when you do need to work with numbers in Python, it offers convenient ways to add, subtract, multiply, divide, round, sort, convert numbers into letters, convert numbers to binary, separate numbers, and a few other handy tricks. In this tutorial, we’ll take a look at how to use integers and floats in Python for use in your programs.

Adding numbers in Python is super easy. Do you know how to use the + sign? Then you know how to add numbers in Python. By adding numbers together, we are getting the sum of the numbers.

### Integers and Floats

Before we start adding numbers, we should quickly discuss what an integer is vs what a float is in Python. An integer (or `int`) data type refers to values that are whole numbers. 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 are all integer values. Numbers that have a decimal point, such as 1.61, are called floating-point numbers (or `floats`). Note that even though the value 12 is an integer, the value 12.0 would be a floating-point number. As a side note, 1.61 is also known as the Golden Ratio – represented by this image.

We can use IDLE, which is an integrated development environment that actually is included with the default installation of Python. It makes it easy to test out snippets of Python code. Here we add some various integers. Just like in math class, Python uses the + operator to add numbers.

Adding floats works in a similar way.

## How To Subtract Numbers In Python

Subtraction is done with the operator. Again we can subtract integer numbers, floating-point numbers, or a mix of the types.

## Divide Numbers

Division is done using the / operator. Notice that you don’t want to divide by zero, lest you run into a ZeroDivisionError.

Python also has an integer division operator //. This floors the quotient for you. In other words, it rounds down the result of the divide operation. Here are a few examples of standard division vs integer floored quotient division.

## How To Multiply Numbers In Python

Numbers can be multiplied together in Python. The * operator handles multiplication for you.

## Exponent Operator

An exponent is a number multiplied by itself a given number of times. The ** operator in Python allows you to calculate exponents like so.

## Find The Remainder

In programming, you often want to find the remainder of a divide operation. This can be done with the modulus operator %.

## Order Of Operations

When doing addition, subtraction, multiplication, division, and so on, there is an order of operations or precedence that is followed. Some math operators have higher precedence than others. This means they are given priority over math operators with lower precedence. The ** operator is evaluated first. The *, /, //, and % operators come next from left to right. Last in the order of operations is the + and operators left to right.
You can use parentheses just like algebra class to override the standard precedence if needed.

#### Python Math Operators From Highest To Lowest Precedence

Operator Operation
** Exponent
% Modulus
// Integer Division
/ Standard Division
* Multiplication
Subtraction

## Rounding Numbers In Python

To round a number in Python you can use the inbuilt round() function. The round() function normally rounds a decimal number to a set number of decimal places given as the second argument. If you leave off the second argument, round() rounds your number to the nearest whole integer.

## Format Numbers

There are all kinds of ways to format numbers in Python. Here are some common examples.

## How To Sort Numbers In Python

Sorting numbers in Python usually happens when you have a list of numbers or some other type of collection of numbers like a tuple or a dictionary of numbers. Imagine we have these numbers stored in a list.

``nums = [1, 3, 2, 5, 4]``

One way we could sort these numbers in Python is by using the built-in sorted() function.

``sorted(nums)``
`[1, 2, 3, 4, 5]`

To sort the numbers in reverse, simply add the second parameter to the sorted() function.

``sorted(nums, reverse=True)``
`[5, 4, 3, 2, 1]`

When using the sorted() function, the original order of the list remains, you are just presenting the numbers in sorted order. The sorted() function displays your list in a particular order but doesnâ€™t affect the actual order of the list. The other option we can use to sort numbers in Python is by using the sort() function.

If we look at our `nums` variable, the sort order is still how it was originally assigned. This shows that the sorted() function left the original list as is.

``nums``
`[1, 3, 2, 5, 4]`

To use the sort() function, we actually used it as a method of the list object. We can see how that syntax differs from sorted() here.

``nums.sort()``
`[1, 2, 3, 4, 5]`

To reverse the sorting order with .sort(), we use the similar reverse=True parameter.

``nums.sort(reverse=True)``
`[5, 4, 3, 2, 1]`

Consider this dictionary that now represents our original collection of numbers.

``nums = {'a': 1, 'b': 3, 'c': 2, 'd': 5, 'e': 4}``

What happens if we try to use the .sort() method here?

``nums.sort()``
```Traceback (most recent call last):
File "<pyshell#100>", line 1, in <module>
nums.sort()
AttributeError: 'dict' object has no attribute 'sort'```

The reason for this is because you can not sort a dictionary, you can only get a representation of a dictionary that is sorted. Dictionaries are inherently borderless. In that case, let’s try the sorted() function since we know that leaves the original data intact, but presents the data in a sorted way. In order for this to work we need to use the .items() method in combination with a lambda function.

``sorted(nums.items(), key= lambda x: x[1])``
`[('a', 1), ('c', 2), ('b', 3), ('e', 4), ('d', 5)]`

To sort the numbers in reverse, you know what to do:

``sorted(nums.items(), key= lambda x: x[1], reverse=True)``
`[('d', 5), ('e', 4), ('b', 3), ('c', 2), ('a', 1)]`

These are the components of using sorted() with a dictionary.

Parameter Syntax Meaning
object nums.items() Refers to all values in our â€śnumsâ€ť dictionary. If we were to use just â€śnumsâ€ť, we would have to reference the index position of the item to get its individual value. On the other hand, if we use nums.items(), an iterable list with the items in a list is created.
key key=lambda x: x[1] A sorting mechanism that allows you to sort a dictionary by value. This is an example of a Lambda function, which is a function without a name.
reverse reverse=True States that we want the numbers to be sorted in reverse, or descending order.

## How To Print Numbers In Python

If you would like to print out a sequence of numbers, you can do that with the range() function in Python. The range() function is used with the `for` construct. It takes three parameters. The first parameter is the number you want to start with. The second parameter is the number you want to count up to, plus one. In other words, if you want to count from 1 to 10, you would use range(1, 11) not range(1, 10).

``````for num in range(1, 11):
print(num)``````
```1
2
3
4
5
6
7
8
9
10```

The third parameter is the step value you want to count by. Say you want to count to 100 by tens. Very easy:

``````for num in range(0, 101, 10):
print(num)``````
```0
10
20
30
40
50
60
70
80
90
100```

It’s also possible to do this in reverse. You can use a negative number in the third parameter to create a countdown effect.

``````for num in range(10, 0, -1):
print(num)``````
```10
9
8
7
6
5
4
3
2
1```

## How To Separate Numbers In Python

If you have a very large number and would like to break it apart into the individual digits, here is how you can do that. We need to use the str() function and a list comprehension.

``````num = 916571163
[int(d) for d in str(num)]``````
`[9, 1, 6, 5, 7, 1, 1, 6, 3]`

## How To Convert Numbers Into Letters In Python

This neat little snippet will print out each letter of the alphabet corresponding to its positional number.

``````import string

for x, y in zip(range(1, 27), string.ascii_uppercase):
print(x, y)``````
```1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J
11 K
12 L
13 M
14 N
15 O
16 P
17 Q
18 R
19 S
20 T
21 U
22 V
23 W
24 X
25 Y
26 Z```

## How To Convert Numbers To Binary In Python

Python offers a bin() function that converts an integer number to a binary string prefixed with â€ś0bâ€ť.

``````num = 123
print(bin(num))``````
`0b1111011`

If you just want the zeros and ones, with no leading 0b, you can use an f-string with the :b format.

``````num = 123
print(f'{num:b}')``````
`1111011`