block1 has data and prev_hash but no attribute named 'hash'.
Step 2: Identify usage of undefined attribute
block2 tries to use block1.hash which does not exist, causing an error.
Final Answer:
block1.hash is not defined before use -> Option A
Quick Check:
Accessing undefined attribute = block1.hash is not defined before use [OK]
Hint: Check if attribute exists before using it [OK]
Common Mistakes:
Assuming hash attribute exists by default
Confusing prev_hash type requirements
Thinking data type causes error
5. You want to create a simple blockchain where each block stores its own hash and the previous block's hash. Which code snippet correctly computes and links the hashes for two blocks?
hard
A. import hashlib
class Block:
def __init__(self, data, prev_hash):
self.data = data
self.prev_hash = prev_hash
self.hash = hashlib.sha256(data.encode()).hexdigest()
block1 = Block('Block 1', '0')
block2 = Block('Block 2', block1.hash)
B. import hashlib
class Block:
def __init__(self, data):
self.data = data
self.hash = hashlib.sha256(data.encode()).hexdigest()
block1 = Block('Block 1')
block2 = Block('Block 2')
block2.prev_hash = block1.hash
C. class Block:
def __init__(self, data, prev_hash):
self.data = data
self.prev_hash = prev_hash
self.hash = data + prev_hash
block1 = Block('Block 1', '0')
block2 = Block('Block 2', block1.hash)
D. import hashlib
class Block:
def __init__(self, data, prev_hash):
self.data = data
self.prev_hash = prev_hash
self.hash = hashlib.sha256((data + prev_hash).encode()).hexdigest()
block1 = Block('Block 1', '0')
block2 = Block('Block 2', block1.hash)
Solution
Step 1: Check hash calculation includes previous hash
The correct implementation computes the hash from both data and prev_hash: self.hash = hashlib.sha256((data + prev_hash).encode()).hexdigest(), ensuring secure linking.
Step 2: Verify other options
B: prev_hash set after hash computation (hash ignores prev_hash); C: no hashing, just concatenation; D: hash ignores prev_hash.
Final Answer:
self.hash = hashlib.sha256((data + prev_hash).encode()).hexdigest() -> Option D
Quick Check:
Hash(data + prev_hash) [OK]
Hint: Hash must include previous hash to link blocks [OK]
Common Mistakes:
Not including prev_hash in hash calculation
Assigning prev_hash after block creation
Using plain concatenation without hashing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.