Lab1: Testing the “Magic Box”
Copy and paste this into your Python terminal to see the magic:
import sys
# 1. Test the "Unlimited" growth
big_number = 10**100
print(f"Google: {big_number}")
# 2. Check memory size of a small vs large number
small_num = 0
huge_num = 10**50
print(f"Size of 0: {sys.getsizeof(small_num)} bytes")
print(f"Size of huge_num: {sys.getsizeof(huge_num)} bytes")
# 3. Integer Interning (Memory Shortcut)
a = 256
b = 256
print(f"Is a same as b? {a is b}") # True (Interned)
c = 300
d = 300
print(f"Is c same as d? {c is d}") # False (Not interned in all environments)
Lab 1: Proving the “Magic Expandable Box”
In this lab, we will calculate a number so large it would crash a standard C++ or Java program (unless using specific BigInt libraries).
# Calculate 2 to the power of 1000
massive_power = 2**1000
print(f"Total Digits: {len(str(massive_power))}")
print(f"The Result: {massive_power}")
# Observation: Notice how Python handles this instantly without an 'Overflow' error.
Lab 2: Detecting “Integer Interning” (The Memory Optimization)
Python saves memory by reusing the same address for small integers. Let’s find the “Boundary.”
def check_interning(n):
x = n
y = n
return x is y # 'is' checks if they share the same memory address
print(f"Is 256 interned? {check_interning(256)}") # Should be True
print(f"Is 257 interned? {check_interning(257)}") # Usually False (depends on Python version/shell)
Lab 3: Security & DoS Protection (The 4,300 Digit Limit)
As a DevSecOps professional, you need to know how Python protects itself from “String Conversion” attacks.
import sys
# Create a very large number (e.g., 5000 digits)
large_val = 10**5000
try:
# Try to convert it to a string (print uses str() internally)
print(str(large_val))
except ValueError as e:
print(f"SECURITY ALERT: {e}")
# Solution: If you NEED to handle larger strings for a specific project:
sys.set_int_max_str_digits(10000)
print("Limit increased. Now I can print it!")
Lab 4: Bitwise Operations for Networking
Integers are often used to calculate Subnet Masks. Let’s see how bitwise AND works.
# IP Address parts in binary
ip_part = 192 # Binary: 11000000
mask_part = 255 # Binary: 11111111
# Bitwise AND
network_id = ip_part & mask_part
print(f"Network ID Part: {network_id}")
print(f"Binary of 192: {bin(ip_part)}")