Mathew K Analytics

Lesson 1 · Python data types deep dive

Python Integers Explained: Bases, Division & Modulo | Data Types #1

Covering every built-in Python data type in full depth, one type per video. This video is entirely about int: every literal form, every operator, and all…

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python Data Types Deep-Dive, Video 1: Integers (int)#

  • Video one of a twelve-part series covering every built-in Python data type in full depth, one type per video.
  • This video is entirely about int: every literal form, every operator, and all ten of its public methods, one at a time.
  • No prior experience with data types needed. Let's get straight into it.

Part 1: What Makes int Different#

small_number = 7
negative_number = -42
zero = 0
huge_number = 99999999999999999999999999999999999999
print(type(small_number))
print(huge_number * huge_number)
<class 'int'>
9999999999999999999999999999999999999800000000000000000000000000000000000001

Part 2: Integer Literals#

readable_million = 1_000_000
binary_literal = 0b1010
octal_literal = 0o17
hex_literal = 0xFF
print(readable_million)
print(binary_literal)
print(octal_literal)
print(hex_literal)
1000000
10
15
255

Part 3: Arithmetic Operators#

a, b = 17, 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
22
12
85
3.4
3
2
1419857
print(-17 // 5)
print(-17 % 5)
print(+a)
print(-a)
-4
3
17
-17

Part 4: Comparison Operators and Chaining#

print(3 < 5)
print(5 <= 5)
print(5 == 5.0)
print(5 != 6)
print(1 < 5 < 10)
print(1 < 10 < 5)
True
True
True
True
True
False

Part 5: Bitwise Operators#

x, y = 0b1100, 0b1010
print(bin(x & y))
print(bin(x | y))
print(bin(x ^ y))
print(bin(~x))
print(bin(x << 2))
print(bin(x >> 2))
0b1000
0b1110
0b110
-0b1101
0b110000
0b11

Part 6: Converting Values to int#

print(int('42'))
print(int('  42  '))
print(int(3.9))
print(int(-3.9))
print(int(True))
print(int(False))
print(int('101', 2))
print(int('ff', 16))
print(int('17', 8))
42
42
3
-3
1
0
5
255
15
try:
    int('not a number')
except ValueError as e:
    print(f'Caught: {e}')
Caught: invalid literal for int() with base 10: 'not a number'

Part 7: Built-in Functions That Work With int#

print(abs(-15))
print(divmod(17, 5))
print(pow(2, 10))
print(pow(2, 10, 1000))
print(round(1234, -2))
print(min(4, 9, 1, 7))
print(max(4, 9, 1, 7))
print(sum([1, 2, 3, 4, 5]))
15
(3, 2)
1024
24
1200
1
9
15

Part 8: bit_length()#

print((0).bit_length())
print((1).bit_length())
print((255).bit_length())
print((256).bit_length())
print((-255).bit_length())
0
1
8
9
8

Part 9: bit_count()#

print((0).bit_count())
print((7).bit_count())
print((8).bit_count())
print((255).bit_count())
print(bin(255))
0
3
1
8
0b11111111

Part 10: to_bytes()#

value = 1024
print(value.to_bytes(2, byteorder='big'))
print(value.to_bytes(2, byteorder='little'))
print(value.to_bytes(4, byteorder='big'))
negative_value = -5
print(negative_value.to_bytes(1, byteorder='big', signed=True))
b'\x04\x00'
b'\x00\x04'
b'\x00\x00\x04\x00'
b'\xfb'
try:
    (300).to_bytes(1, byteorder='big')
except OverflowError as e:
    print(f'Caught: {e}')
Caught: int too big to convert

Part 11: from_bytes()#

encoded = (1024).to_bytes(2, byteorder='big')
print(int.from_bytes(encoded, byteorder='big'))
print(int.from_bytes(encoded, byteorder='little'))
signed_encoded = (-5).to_bytes(1, byteorder='big', signed=True)
print(int.from_bytes(signed_encoded, byteorder='big', signed=True))
print(int.from_bytes(signed_encoded, byteorder='big', signed=False))
1024
4
-5
251

Part 12: as_integer_ratio()#

print((5).as_integer_ratio())
print((-5).as_integer_ratio())
print((0).as_integer_ratio())
(5, 1)
(-5, 1)
(0, 1)

Part 13: numerator and denominator#

value = 42
print(value.numerator)
print(value.denominator)
from fractions import Fraction
print(Fraction(value.numerator, value.denominator))
42
1
42

Part 14: real and imag#

value = 42
print(value.real)
print(value.imag)
print(type(value.real))
42
0
<class 'int'>

Part 15: conjugate()#

print((42).conjugate())
print((-7).conjugate())
print((42).conjugate() == 42)
42
-7
True

Part 16: Formatting Integers#

value = 1234567
print(f'{value:,}')
print(f'{value:_}')
print(f'{value:010d}')
print(f'{value:+d}')
print(f'{value:x}')
print(f'{value:#x}')
print(f'{value:o}')
print(f'{value:b}')
print(format(value, ','))
1,234,567
1_234_567
0001234567
+1234567
12d687
0x12d687
4553207
100101101011010000111
1,234,567

Part 17: Arbitrary Precision, No Overflow#

import math
factorial_100 = math.factorial(100)
print(factorial_100)
print(len(str(factorial_100)))
print(2 ** 200)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
158
1606938044258990275541962092341162602522202993782792835301376

Part 18: Small Integer Caching and Identity#

a = 100
b = 100
print(a is b)
c = 1000
d = 1000
print(c is d)
print(c == d)
True
False
True

Part 19: Immutability#

value = 5
print(id(value))
value = value + 1
print(id(value))
value += 1
print(id(value))
140734169889336
140734169889368
140734169889400

Part 20: Common Patterns and Pitfalls#

def is_even(n):
    return n % 2 == 0
print(is_even(4))
print(is_even(7))
print(is_even(-4))
True
False
True
try:
    result = 10 // 0
except ZeroDivisionError as e:
    print(f'Caught: {e}')
Caught: integer division or modulo by zero
print(type(10 / 2))
print(type(10 // 2))
average = (3 + 4) / 2
print(average)
<class 'float'>
<class 'int'>
3.5

Wrap-Up: What You Learned#

  • Integer literals: decimal, underscores, binary, octal, and hexadecimal.
  • Every arithmetic, comparison, and bitwise operator, including floor division and modulo with negative numbers.
  • Converting to int with int(), including parsing strings in any base.
  • Built-in functions that operate on integers: abs, divmod, pow, round, min, max, sum.
  • All ten public int methods: bit_length, bit_count, to_bytes, from_bytes, as_integer_ratio, numerator, denominator, real, imag, and conjugate.
  • Formatting integers with f-strings and format().
  • Arbitrary precision, small-integer caching, immutability, and the true-division-versus-floor-division distinction.
  • Next up in this series: float, the second numeric type, and where its extra methods and rounding behavior genuinely diverge from int.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. What does this print?

    print(-17 // 5, -17 % 5)
    
  2. What type does 10 / 2 produce in Python 3?

  3. What does this print?

    print((256).bit_length(), (255).bit_count())
    
  4. Why should you compare integer values with == and not is?

  5. What does this print?

    print(pow(2, 10, 1000))
    

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Given n = 1234567, print it with comma separators, then print it in binary, then in hexadecimal (all using f-string format specs).

    💡 Hint

    Use format specs like :, then :b and :x.

    ✅ Show solution
    n = 1234567
    print(f"{n:,}")   # 1,234,567
    print(f"{n:b}")   # binary digits
    print(f"{n:x}")   # hexadecimal digits
    
  2. Write digit_sum(n) that returns the sum of the digits of a non-negative integer using divmod (no string conversion). digit_sum(4821) should be 15.

    💡 Hint

    Loop with divmod(n, 10) to peel off the last digit each time.

    ✅ Show solution
    def digit_sum(n):
        total = 0
        while n > 0:
            n, last = divmod(n, 10)  # split off the last digit
            total += last
        return total
    
    print(digit_sum(4821))
    assert digit_sum(4821) == 15
    assert digit_sum(0) == 0
    
  3. Write to_base(n, base) that converts a non-negative integer to a string in any base from 2 to 16 without using bin/hex/format. Check it against int(text, base).

    💡 Hint

    Repeatedly divmod by the base and collect digits from a lookup string, then reverse.

    ✅ Show solution
    DIGITS = "0123456789abcdef"
    
    def to_base(n, base):
        if n == 0:
            return "0"
        out = []
        while n > 0:
            n, r = divmod(n, base)   # remainder is the next digit
            out.append(DIGITS[r])
        return "".join(reversed(out))  # digits came out last-first
    
    for n in (0, 5, 255, 1024, 99999):
        for base in (2, 8, 16):
            text = to_base(n, base)
            assert int(text, base) == n
    print(to_base(255, 2), to_base(255, 16))
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.