CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 2
1.8 Computer memory: how values are stored
Study notes for Computer memory: how values are stored in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in StudyCat.
Big ideas
- Memory is a huge row of bytes, each of 8 bits. Everything (numbers, text, code) is stored as patterns of bits; 210 = 1024 bytes is a kibibyte, and binary 1011 is 8 + 2 + 1 = 11.
- A Python variable is a name that refers to an object somewhere in memory.
id(x)shows the address; two names can refer to the same object. - Ints, floats and strings are immutable:
y = x; y += 1makes y refer to a new object and leaves x alone. Lists (soon) are mutable, so two names for the same list see each other’s changes. - Floats are binary fractions with limited precision, which is why
0.1 + 0.2 == 0.3is False. Compare floats with a tolerance orround(). - Function calls stack up frames (their local variables); a frame is freed when the call returns. Python frees objects nobody refers to anymore.
Code you should know
Names, objects and immutability
x = 5
y = x
y += 1
print(x, y, x is y)
a = "cat"
b = a
b = b + "s"
print(a, b)
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, round(0.1 + 0.2, 2) == 0.3)Output
5 6 False cat cats 0.30000000000000004 False True
Bits, bytes and binary
print(bin(11), int("1011", 2), 2 ** 10)
print(ord("A"), chr(65), bin(ord("A")))
for n in range(0, 9):
print(n, format(n, "04b"))Output
0b1011 11 1024 65 A 0b1000001 0 0000 1 0001 ...
Worked example
Convert binary 110101 to decimal and 45 to binary.
Show the solution
110101 = 32 + 16 + 4 + 1 = 53. 45 = 32 + 8 + 4 + 1 = 101101 (subtract the largest power of two that fits, repeat).
Common mistakes
- Thinking
y = xcopies a number “by value” in some special way: both names refer to the same object until one is reassigned; for immutable objects that is indistinguishable from copying. - Testing float results with
==. - Mixing up bits and bytes (8 bits per byte).
Exam tipBe able to convert small binary numbers by hand and to explain, in one sentence, why
0.1 + 0.2 is not exactly 0.3.Keep going in StudyCat
StudyCat is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.