Here’s a comprehensive, inline explanation of:
- Python Numbers (int, float, complex)
- Boolean Values
- Type Conversion
- Number Formatting
- Memory Size using
sys.getsizeof()
- How Python Interpreter Reads, Parses, Executes Code
- How Output Is Generated and Passed
🧮 1. Python Numbers
A. Integer (int
)
- Whole numbers without a decimal.
- Can be arbitrarily large in Python (limited by memory, not 32/64 bits).
x = 42
print(type(x)) # <class 'int'>
B. Floating Point (float
)
- Numbers with decimals. Internally stored using 64-bit IEEE-754 format.
y = 3.14
print(type(y)) # <class 'float'>
C. Complex Numbers (complex
)
- Numbers with real and imaginary parts.
z = 3 + 4j
print(type(z)) # <class 'complex'>
✅ 2. Boolean Values
True
andFalse
are the only Boolean values.- Internally,
True == 1
,False == 0
.
a = True
b = False
print(int(a), int(b)) # Output: 1 0
Useful in conditions:
if True:
print("This runs.")
🔁 3. Type Conversion (Casting)
Implicit Conversion
Python automatically converts:
a = 10 # int
b = 2.5 # float
result = a + b # float (a gets converted)
print(result) # 12.5
Explicit Conversion
Use int()
, float()
, str()
etc.:
print(int(3.99)) # 3
print(float("5")) # 5.0
print(str(100)) # '100'
🎯 4. Number Formatting
Using format()
or f-strings:
num = 1234.56789
print(f"{num:.2f}") # 1234.57 (2 decimal places)
print(f"{num:,.2f}") # 1,234.57 (comma and 2 decimals)
With format()
function:
print(format(num, ".1f")) # '1234.6'
🧠 5. Memory Size with sys.getsizeof()
To inspect how much memory a variable uses:
import sys
x = 10
y = 10.5
print(sys.getsizeof(x)) # e.g., 28 bytes
print(sys.getsizeof(y)) # e.g., 24 bytes
Even a simple int
or float
includes metadata (like reference count, type info), so memory usage is more than just value size.
⚙️ 6. How Python Reads and Executes Code
Behind the Scenes — From Code to Execution
1. Lexical Analysis (Tokenization)
Python splits the source code into tokens:
x = 10 + 5
Tokens: x
, =
, 10
, +
, 5
2. Parsing
Parser builds an Abstract Syntax Tree (AST), representing code structure.
Assign(
targets=[Name(id='x')],
value=BinOp(left=Num(n=10), op=Add(), right=Num(n=5))
)
3. Bytecode Compilation
Python converts AST to bytecode, a low-level set of instructions:
>>> import dis
>>> def add(): x = 10 + 5
>>> dis.dis(add)
2 0 LOAD_CONST 1 (10)
2 LOAD_CONST 2 (5)
4 BINARY_ADD
6 STORE_FAST 0 (x)
8 LOAD_CONST 0 (None)
10 RETURN_VALUE
4. Execution by Python Virtual Machine (PVM)
The bytecode is executed line-by-line by the interpreter’s virtual machine.
🖨️ 7. How Output Is Collected and Passed
print()
function calls the built-insys.stdout.write()
.- Output is flushed from a buffer to the console.
Behind print()
print("Hello")
# Equivalent to:
import sys
sys.stdout.write("Hello\n")
- If you redirect stdout, output goes to file or stream:
with open("log.txt", "w") as f:
print("Log this", file=f)
🧬 Internals Summary
Concept | How Python Handles It |
---|---|
Variable Storage | Stored as objects in memory; variable is just a name pointing to object |
Numbers | int and float objects, dynamically sized |
Booleans | Subclass of int (True == 1, False == 0) |
Memory Allocation | Managed by Python’s memory manager and garbage collector |
Output Display | Uses sys.stdout ; buffered write to console |
Execution Engine | Python Virtual Machine interprets bytecode |
🔚 Examples Recap
import sys
x = 42
y = 3.14
z = 1 + 2j
flag = True
print(type(x), sys.getsizeof(x))
print(type(y), sys.getsizeof(y))
print(type(z), sys.getsizeof(z))
print(type(flag), int(flag), sys.getsizeof(flag))
x, y = y, x # Swapping using multiple assignment
print(f"Swapped: x = {x}, y = {y}")
num = 1234.5678
print(f"Formatted: {num:,.2f}") # Comma, 2 decimal places
# Bytecode
import dis
dis.dis(lambda: 2 + 3)
✅ Let’s dive into why x = 10; x
prints the value in some environments without using print(x)
.
🔍 Scenario: Just writing x
after x = 10
✅ In Python REPL (Read-Eval-Print Loop), Jupyter Notebooks, or IPython, this:
x = 10
x
outputs:
10
🧠 Why It Works:
These environments are designed to behave interactively:
- When you enter an expression (like
x
) on its own line, the interpreter:- Evaluates it
- Automatically prints the result
This is part of the print(repr(result))
step done behind the scenes in REPL/Notebook sessions.
🔧 Internals:
In interactive mode:
- Only the value of the last unassigned expression is echoed to the output.
- It’s as if this happens:
_result = eval('x')
print(repr(_result))
❌ In Regular .py
Scripts:
If you write the same code in a .py
file:
x = 10
x
You won’t see any output, because:
- The value
x
is computed but not printed. - Python scripts don’t auto-display the value of expressions unless explicitly told using
print()
.
✅ Use print()
in scripts:
x = 10
print(x) # Output: 10
🧪 Test It Yourself:
Environment | Will x alone show output? |
---|---|
Python REPL | ✅ Yes |
Jupyter Notebook | ✅ Yes |
IPython shell | ✅ Yes |
VS Code Interactive | ✅ Yes |
Python .py script | ❌ No (use print(x) ) |
🔄 Recap:
- ✅ In interactive environments, expressions are automatically printed.
- ❌ In scripts, expressions must be passed to
print()
for output.
Leave a Reply