Python Numbers

Working with Integers

In Python, integers (represented by the int data type) are whole numbers, including positive, negative, and zero. Unlike some other programming languages, integers in Python have unlimited precision, meaning they can theoretically store numbers as large as your computer's memory allows.


1. Representing integers

You can create integers simply by assigning whole numbers to variables:

age = 30
count = -10
binary_number = 0

Integers can also be represented in different bases (binary, octal, hexadecimal) for specific use cases. Python allows you to specify the base using an underscore prefix followed by the base indicator (e.g., 0b1101 for binary, 0o123 for octal, 0xCAFE for hexadecimal).


2. Operations on integers

Python supports basic arithmetic operations like addition (+), subtraction (-), multiplication (*), and integer division (//). These operations behave as you would expect for whole numbers.

There's also the modulo operator (%) that gives you the remainder after a division. For example, 10 % 3 would be 1 (remainder after dividing 10 by 3).


3. Things to keep in mind

When dividing integers by integers, Python performs integer division. This means the result will always be an integer, even if the mathematical answer is a fraction. The fractional part is truncated. To get a floating-point result, you can convert one of the operands to a float before division:

result1 = 10 // 3  # result1 will be 3 (integer division)
result2 = 10.0 / 3  # result2 will be 3.3333... (float division)

Integers can't directly represent decimal places. If you need to store numbers with decimals, you should use the float data type.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

Which of the following is a valid representation of an integer in Python?

all of the above
0b1101
0o123
0xCAFE
Check Answer

What is the result of the operation 10 % 3?

3
1
10
0
Check Answer

What will be the result of 10 // 3 in Python?

2.5
3
3.0
4
Check Answer

Which data type should be used to store numbers with decimal places in Python?

int
float
complex
str
Check Answer

How would you represent the binary number 1011 in Python?

0b11
binary(1011)
0b1011
1011b
Check Answer