The magic fingerprint behind every block
Yesterday we said "change one character and the chain breaks." Today you'll see exactly why — and write the Python to prove it.
Feed a hash function any input — a word, a sentence, an entire book. It always produces an output of exactly the same length. Change even one character and the output is completely different.
import hashlib
def sha256(text):
return hashlib.sha256(text.encode()).hexdigest()
print(sha256("hello"))
# → 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
print(sha256("Hello")) # Capital H
# → 185f8db32921bd46d35cc88b7422e0fcedb2b3f0f7b1460c4b02b2cdc45a6f8Same input always gives same output. Hash("hello") is always the same value, every time, on every computer.
No matter how long the input, the output is always 64 hex characters (256 bits for SHA-256).
You can go from data → hash instantly. You cannot go hash → data. It's a one-way door.
Change one bit of input and roughly half the output bits flip. Small change = completely different fingerprint.
import hashlib
text = "Polkadot block #21000000"
hash_value = hashlib.sha256(text.encode()).hexdigest()
print(hash_value)
# → some 64-character hex string
# Step by step:
# text.encode() → converts string to bytes
# hashlib.sha256(...) → creates SHA-256 hash object
# .hexdigest() → returns result as hex stringAlways exactly 64 hex chars = 256 bits. Every block on every blockchain has one of these.
The output uses 0-9 and a-f. You saw hex in Day 2 of the old syllabus — it's just base-16.
import hashlib
def h(t): return hashlib.sha256(t.encode()).hexdigest()
print(h("blockchain"))
# 5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9
print(h("Blockchain")) # capital B
# ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f
print(h("blockchain!")) # added !
# 9c827201a94b6c9e3b2aaa7e76f55e3ead3f0e8d2e67c3a25b0a1c07af6af3e1prev_hash now points to the old, wrong hash. The chain is invalid — and anyone can see it.
Hash 5 different strings. Then for each one, change a single character and hash again. Print both side by side and note how different they are.
Convert a dict to a string (use str()), hash it. Change one value in the dict, hash again. Prove the hash is different — this is exactly how blocks work.
students/<username>/D22_hashing.py. PR before 12:00.
hashlib.sha256().