# Numbers in Python: Operators, Precision, Number Systems, and Useful Libraries

*Learning Python with Chai aur Code, one video at a time.*

**Learning source:** [Chai aur Code — Python Video 8](https://www.youtube.com/watch?v=E4GNbP4SbKM)

In this lesson, I explored how Python handles numbers and the different operations we can perform on them. I also learned about number precision, mathematical libraries, number systems, Boolean values, and sets.

At first, these topics might look like a collection of unrelated concepts. But they help us understand how Python works with data and how we can perform calculations more effectively.

Let's go through them one by one.

## 1\. Understanding Numbers in Python

Python has several numeric types. Numbers are not represented by one single type; instead, Python provides different types of numeric objects.

Some common numeric types are:

| Type | Example | Description |
| --- | --- | --- |
| `int` | `10` | Integers |
| `float` | `10.5` | Floating-point numbers |
| `complex` | `2 + 3j` | Complex numbers |
| `bool` | `True`, `False` | Boolean values, also a subtype of integers |

To check the type of any value, we can use the built-in `type()` function.

```python
print(type(10))       # <class 'int'>
print(type(10.5))     # <class 'float'>
print(type(2 + 3j))   # <class 'complex'>
print(type(True))     # <class 'bool'>
```

Python also supports very large integers. Unlike languages that use fixed-width integer types, Python integers can grow to very large values, limited mainly by available memory.

For example:

```python
number = 1234567890123456789012345678901234567890
print(number)
```

Python can handle this without requiring us to choose a larger integer type manually.

It also supports complex numbers, which have a real and an imaginary part.

```python
number = 2 + 3j
print(type(number))   # <class 'complex'>
```

Python's numerical capabilities can be extended further using libraries such as **NumPy** and **SciPy**. These are widely used for scientific computing, mathematical operations, and data analysis.

For context, MATLAB stands for **MATrix LABoratory**. It is a programming language and numerical computing environment used in mathematical computations, simulations, engineering, and data analysis. Python, together with libraries such as NumPy and SciPy, can perform many similar kinds of tasks.

## 2\. Basic Arithmetic Operators

Python supports the usual mathematical operations.

| Operator | Meaning | Example | Output |
| --- | --- | --- | --- |
| `+` | Addition | `10 + 5` | `15` |
| `-` | Subtraction | `10 - 5` | `5` |
| `*` | Multiplication | `10 * 5` | `50` |
| `/` | Division | `10 / 5` | `2.0` |
| `//` | Floor division | `10 // 3` | `3` |
| `**` | Exponentiation | `2 ** 3` | `8` |
| `%` | Modulus (remainder) | `10 % 3` | `1` |

One operator worth understanding properly is `//`.

### What is floor division?

Floor division divides two numbers and rounds the result down to the nearest integer value.

```python
print(10 // 3)    # 3
print(10 // 4)    # 2
print(-10 // 3)   # -4
```

Notice the last example. Floor division rounds towards negative infinity, not towards zero.

This distinction becomes important when working with negative numbers.

## 3\. Operator Precedence and Parentheses

Consider this expression:

```python
x = 10
y = 5
z = 2

print(x + y * z)
```

The output is:

```text
20
```

Why?

Because multiplication is evaluated before addition.

Python follows operator precedence rules to decide which operation should happen first.

However, rather than memorizing the entire precedence table, a useful habit is to use parentheses whenever you want to make the intended order of operations clear.

```python
print((x + y) * z)   # 30
print(x + (y * z))   # 20
```

Parentheses make the intention easier to understand, especially when expressions become complicated.

## 4\. Working With Different Numeric Types

Python allows operations between certain different numeric types.

For example:

```python
print(40 + 2.2)   # 42.2
```

Python converts the integer to a floating-point value for the operation.

However, mixing unrelated types can produce errors:

```python
print("ad" + 2)
```

This raises a `TypeError` because Python does not automatically convert the integer `2` into a string for concatenation.

We can explicitly convert values using functions such as:

```python
print(int(2.2))       # 2
print(float(40))      # 40.0
print(int(True))      # 1
print(int(False))     # 0
```

Remember that Python is case-sensitive:

```python
true = 10       # This is a variable name
True            # The actual Boolean value
```

The correct Boolean values are `True` and `False`, with capital first letters.

**An important exception:** Complex numbers cannot be directly converted to `int` or `float` because that would discard their imaginary component.

```python
number = 2 + 3j

# int(number)    # TypeError
# float(number)  # TypeError
```

The general idea is to make your intention clear when converting or combining different data types.

## 5\. Formatting Numbers for Display

Consider this calculation:

```python
print(1 / 3)
```

Output:

```text
0.3333333333333333
```

Sometimes displaying so many decimal places is unnecessary. We can use an f-string to control how a number is displayed.

```python
print(f"{1 / 3:.2f}")
```

Output:

```text
0.33
```

Let's understand the syntax:

- `f` makes it an f-string.
- `{}` contains the expression or variable.
- `:.2f` means display the number as a floating-point value with two digits after the decimal point.

We can also use a variable:

```python
number = 1 / 3

print(f"{number:.2f}")   # 0.33
print(f"{number:.4f}")   # 0.3333
print(f"{number:.6f}")   # 0.333333
```

You can change the number after the decimal point to control how many digits are displayed.

**One important thing to remember:** Formatting changes how the number is displayed, not the actual value stored in the variable.

## 6\. Comparison Operators

Comparison operators are used to compare values. Their results are Boolean values: `True` or `False`.

| Operator | Meaning |
| --- | --- |
| `<` | Less than |
| `>` | Greater than |
| `==` | Equal to |
| `!=` | Not equal to |
| `<=` | Less than or equal to |
| `>=` | Greater than or equal to |

Example:

```python
x = 10
y = 20

print(x < y)    # True
print(x > y)    # False
print(x == y)   # False
print(x != y)   # True
```

### Chained comparisons

Python allows us to combine comparisons in a shorthand form.

```python
x = 10
y = 20
z = 30

print(x < y < z)
```

Output:

```text
True
```

This is equivalent to:

```python
print(x < y and y < z)
```

Python evaluates both comparisons and combines their results.

Chained comparisons are a normal and useful Python feature, not something we need to avoid.

Another interesting example:

```python
print(1 == 2 < 3)
```

Output:

```text
False
```

This is interpreted as:

```python
print((1 == 2) and (2 < 3))
```

It is not interpreted as `(1 == 2) < 3`.

## 7\. Operator Overloading

Python supports something called **operator overloading**.

It means the same operator can perform different operations depending on the types of its operands.

For example, look at the `+` operator:

```python
print(10 + 20)             # 30
print("Hello" + "World")   # HelloWorld
print([1, 2] + [3, 4])     # [1, 2, 3, 4]
```

The same `+` operator performs three different operations:

- With numbers, it performs addition.
- With strings, it joins them together.
- With lists, it concatenates the lists.

Python decides what the operator should do based on the objects involved.

## 8\. Multiple Values and Tuples

Python can group multiple values into a tuple.

For example:

```python
x = 1
y = 2

result = x, y

print(result)        # (1, 2)
print(type(result))  # <class 'tuple'>
```

Even though `x` and `y` are separate variables, writing `x, y` as an expression creates a tuple.

We can also assign multiple values at once:

```python
x, y = 1, 2

print(x)   # 1
print(y)   # 2
```

This is called multiple assignment or unpacking.

## 9\. Difference Between `repr()`, `str()`, and `print()`

These three are related, but they serve different purposes.

Let's take a string:

```python
value = "hi"

print(repr(value))
print(str(value))
print(value)
```

Output:

```text
'hi'
hi
hi
```

Here's the difference:

`repr()`

Returns a representation of an object that is useful for debugging. For strings, it includes quotation marks so that we can see where the string begins and ends.

```python
print(repr("hi"))   # 'hi'
```

`str()`

Returns a readable string representation of an object.

```python
print(str("hi"))    # hi
```

`print()`

Displays values to the output. It converts the values to strings for display, using their string representation.

```python
print("hi")         # hi
```

A simple way to remember:

- `repr()` is generally useful for debugging and inspecting objects.
- `str()` is useful when we want a readable string representation.
- `print()` displays the result.

## 10\. Mathematical Libraries in Python

Python has built-in modules that provide additional mathematical functionality.

### The `math` module

We can import it using:

```python
import math
```

Two useful functions are `floor()` and `trunc()`.

`math.floor()`

Returns the greatest integer less than or equal to the given number.

```python
print(math.floor(3.5))    # 3
print(math.floor(-3.5))   # -4
```

`math.trunc()`

Removes the decimal part and moves towards zero.

```python
print(math.trunc(3.5))    # 3
print(math.trunc(-3.5))   # -3
```

The difference becomes clear with negative numbers:

- `floor(-3.5)` gives `-4`.
- `trunc(-3.5)` gives `-3`.

### The `random` module

We can generate random values using:

```python
import random
```

Some useful functions:

`random.random()`

Returns a random floating-point number greater than or equal to `0.0` and less than `1.0`.

```python
print(random.random())
```

It does not require any arguments.

`random.randint(a, b)`

Returns a random integer between `a` and `b`, including both endpoints.

```python
print(random.randint(1, 100))
```

This can return any integer from `1` through `100`, including `100`.

`random.choice(sequence)`

Selects one random element from a non-empty sequence, such as a list, tuple, or string.

```python
l1 = [10, 20, 30, 40]

print(random.choice(l1))
```

`random.shuffle(list)`

Shuffles a mutable sequence in place. It changes the original list rather than creating a new shuffled list.

```python
l1 = [1, 2, 3, 4, 5]

random.shuffle(l1)

print(l1)
```

The order will be randomized.

One important detail: `shuffle()` returns `None`, so we should not write `l1 = random.shuffle(l1)`.

## 11\. Different Number Systems

Apart from the decimal number system that we commonly use, Python supports other number systems.

| Number system | Base | Prefix | Example | Decimal value |
| --- | --: | --- | --- | --: |
| Decimal | 10 | None | `20` | 20 |
| Binary | 2 | `0b` | `0b1000` | 8 |
| Octal | 8 | `0o` | `0o20` | 16 |
| Hexadecimal | 16 | `0x` | `0x20` | 32 |

We don't need to manually convert every number. Python provides functions for this.

```python
print(bin(34))   # 0b100010
print(oct(24))   # 0o30
print(hex(64))   # 0x40
```

### Converting numbers using `int()`

We can also use `int()` to convert a string representing a number from a particular base into a decimal integer.

```python
print(int("34", 8))    # 28
print(int("34", 16))   # 52
print(int("1000", 2))  # 8
```

The second argument tells Python which base to use.

Remember the allowed digits:

- Binary (base 2): `0` and `1`
- Octal (base 8): `0` to `7`
- Decimal (base 10): `0` to `9`
- Hexadecimal (base 16): `0` to `9` and `A` to `F`

For example:

```python
int("12", 2)
```

This raises a `ValueError` because `2` is not a valid digit in binary.

## 12\. Bitwise Operators

Bitwise operators work directly on the binary representation of integers.

This is a wider topic on its own, but here are the main operators:

| Operator | Meaning |
| --- | --- |
| `&` | Bitwise AND |
| `\|` | Bitwise OR |
| `^` | Bitwise XOR |
| `~` | Bitwise NOT |
| `<<` | Left shift |
| `>>` | Right shift |

For example:

```python
print(5 & 3)
print(5 | 3)
print(5 ^ 3)
print(5 << 1)
print(5 >> 1)
```

Bitwise operations are useful in areas such as low-level programming, flags, permissions, and certain optimization tasks.

I won't go deeply into them here because they deserve a separate explanation.

## 13\. Why Does Floating-Point Precision Sometimes Cause Problems?

This was one of the interesting parts of the lesson.

Consider these two calculations:

```python
print((0.1 + 0.1 + 0.1) - 0.3)
print(0.1 + 0.1 - 0.2)
```

You might expect both results to be exactly `0`.

However, the first calculation can produce something like:

```text
5.551115123125783e-17
```

while the second produces:

```text
0.0
```

Why does this happen?

Computers store ordinary floating-point numbers using binary representations. Some decimal fractions, such as `0.1`, cannot be represented exactly in binary.

As a result, the stored values are very close to the decimal values we intended, but not always exact.

When we perform calculations using these approximations, tiny differences can appear.

### Using the `decimal` module

Python provides the `decimal` module for decimal arithmetic where exact decimal representation is important.

```python
from decimal import Decimal

result = (
    Decimal("0.1")
    + Decimal("0.1")
    + Decimal("0.1")
    - Decimal("0.3")
)

print(result)   # 0.0
```

Notice that we pass the decimal values as strings.

This is important because creating a `Decimal` from a float can carry over the float's existing approximation.

The `decimal` module also provides a context that controls precision and rounding behaviour.

### Using the `fractions` module

Python also provides the `fractions` module, which allows us to work with rational numbers.

```python
from fractions import Fraction

myf = Fraction(2, 7)

print(myf)          # 2/7
print(myf + myf)    # 4/7
```

Instead of approximating a fraction as a floating-point number, `Fraction` can represent it exactly.

## 14\. Sets in Python

A set is a collection that stores unique elements.

For example:

```python
s = {1, 2, 3, 4, 4}

print(s)
```

Output:

```text
{1, 2, 3, 4}
```

Notice that the duplicate `4` is automatically removed.

Sets are useful when we want to work with unique values or perform mathematical set operations.

### Creating an empty set

There is one small detail worth remembering:

```python
s = set()
```

This creates an empty set.

But:

```python
s = {}
```

creates an empty dictionary, not an empty set.

### Set operations

Some commonly used set operators are:

**Intersection (**`&`**)**

Returns the elements common to both sets.

```python
a = {1, 2, 3}
b = {2, 3, 4}

print(a & b)    # {2, 3}
```

**Union (**`|`**)**

Combines elements from both sets without duplicates.

```python
print(a | b)    # {1, 2, 3, 4}
```

Sets are not numeric types, but they support mathematical operations such as union and intersection.

## 15\. Boolean Values and Numbers

Python has two Boolean values:

```python
True
False
```

An interesting fact is that `bool` is a subclass of `int` in Python.

This means Boolean values behave like `1` and `0` in many numerical operations.

```python
print(True == 1)      # True
print(False == 0)     # True

print(True + 2)       # 3
print(False + 2)      # 2
```

But there is an important difference between equality (`==`) and identity (`is`).

```python
print(True == 1)   # True
print(True is 1)   # False
```

Why?

- `==` checks whether two values are equal.
- `is` checks whether two references point to the exact same object.

So, `True` behaves numerically like `1`, but it is not the same object as the integer `1`.

This is why we should not confuse equality with identity.

---

## Key Takeaways

Here are the concepts I want to remember from this lesson:

1. Python supports multiple numeric types, including integers, floats, and complex numbers.
2. Python integers can handle very large values, while floating-point numbers can have precision limitations.
3. `//` performs floor division, while `%` returns the remainder.
4. Parentheses help make the intended order of operations clear.
5. The same operator can behave differently depending on the types involved. This is called operator overloading.
6. `repr()`, `str()`, and `print()` serve different purposes.
7. The `math`, `random`, `decimal`, and `fractions` modules provide useful functionality.
8. Python supports binary, octal, and hexadecimal number systems.
9. Sets store unique elements and support operations such as union and intersection.
10. Boolean values behave numerically like `1` and `0`, but they are not identical to those integer objects.

## Final Thoughts

This lesson helped me understand that working with numbers in Python is not limited to basic addition, subtraction, or multiplication.

There are different numeric types, different ways to represent numbers, and different libraries depending on the kind of calculation we want to perform.

The floating-point precision example was especially interesting because it showed that even a simple calculation can behave differently from what we might expect.

I'm also beginning to see how Python's built-in features and libraries make it useful for much more than writing basic programs.

**If you have any suggestions, corrections, or interesting examples related to these concepts, feel free to share them. I'm documenting what I learn one lesson at a time, and feedback is always welcome!**
