Computer Science › Section B · Data storage › Topic B.8
Data and programming
A programming language lets you name data and compute with it without handling bit patterns yourself. A first look at Python shows how integers, floats and text from the earlier topics appear in real code, and what goes wrong when types are mixed up.
From bit patterns to programs
The earlier topics showed how integers, fractions and text become bit patterns. A programming language hides that work: you write values and operations, and the language chooses and manages the representations. This topic uses Python 3, a popular first language that is free to download. Python is interpreted, which means its instructions are carried out one at a time by a program called the interpreter. You can type a line at the interactive prompt, shown as >>>, and see the result at once, or save many lines in a file ending in .py, called a script, and run them all together.
A first statement
The traditional first program displays a message: print('Hello, data!'). Here print is a built-in function, an operation the language already provides, and the parentheses hold the value it should display. The quotation marks, single or double, mark a string: a sequence of characters, stored with a character encoding such as UTF-8. Without quotes, print(Hello) makes Python treat Hello as a name and stop with a NameError, since nothing has that name. Anything after a # on a line is a comment, a note for human readers that Python ignores, as in print(2 ** 10) # shows 1024.
Variables and assignment
A variable is a name that refers to a value. The assignment statement count = 5 stores 5 under the name count. The = sign means "store the value on the right under the name on the left", not "is equal to", so count = count + 1 is perfectly legal: Python works out the right side, 6, then updates count. Names may contain letters, digits and underscores but may not start with a digit, and they are case-sensitive, so Total and total are different variables. Reserved words such as if, for and while cannot be names. Python is dynamically typed: you never declare a type, because each value carries its own.
Types and their representations
Each value has a type, which the function type() reports. An int is a whole number; unlike the fixed-width integers of the topic on two's complement, Python's int grows as needed, limited only by memory, so 2 ** 100 prints all 31 digits exactly and does not overflow. A float is normally an IEEE 754 double, which is why 0.1 + 0.2 shows 0.30000000000000004. A bool is True or False, and a str is text. The literals 0xFF and 0b11111111 are just other ways to write 255; the stored value is identical, and print shows it in decimal. The functions bin(45), hex(255) and int('101101', 2) give '0b101101', '0xff' and 45.
Arithmetic operators
Python uses + for addition, - for subtraction and * for multiplication. The operator / always gives a float, so 6 / 3 is 2.0 and 7 / 2 is 3.5. For whole-number results, // is floor division and % gives the remainder: 17 // 5 is 3 and 17 % 5 is 2, since \(5 \times 3 + 2 = 17\). Powers use **, so 2 ** 10 is 1024. As in algebra, ** is done first, then *, /, // and %, then + and -, and parentheses override everything. Beware: ^ is not a power in Python. It is a bitwise operator, and 2 ^ 3 gives 1.
Worked example: splitting a time
A video lasts 7,384 seconds. Show it in hours, minutes and seconds. 1. total = 7384 stores the length. 2. hours = total // 3600 gives 2, because 3,600 seconds make an hour and floor division drops the fraction. 3. rest = total % 3600 gives 184, the seconds left over after 2 full hours. 4. minutes = rest // 60 gives 3. 5. seconds = rest % 60 gives 4. 6. print(hours, 'h', minutes, 'min', seconds, 's') displays 2 h 3 min 4 s, since print separates its items with spaces. 7. Check: \(2 \times 3600 + 3 \times 60 + 4 = 7384\). Using / instead would give 2.0511..., which is not what the task wants.
Working with strings
Strings have their own uses of the operators: + joins them, so 'data' + 'base' is 'database', and * repeats them, so 'ha' * 3 is 'hahaha'. Mixing a string and a number with + is an error, because Python will not guess whether you meant arithmetic or joining: 'Total: ' + 5 fails. Convert explicitly instead. str(7) + '7' gives '77'; int('42') + 1 gives 43; float('2.5') gives 2.5. Note that int(3.99) gives 3, because int() drops the fraction rather than rounding, and int('3.5') fails because the text is not a whole number. Printing with commas, as in print('Total:', 5), converts each item for you.
Three kinds of error
Errors in programs are called bugs, and finding them is debugging. A syntax error breaks the grammar of the language, such as a missing closing parenthesis; Python refuses to run the script at all. A runtime error, called an exception in Python, happens while the program runs and stops it at that line: TypeError for mixed-up types, ZeroDivisionError for 1 / 0, ValueError for int('3.5'). A logic error is the most dangerous: the program runs without complaint and gives a wrong answer. Testing against cases whose answers you already know is the main way to reveal it.
Worked example: debugging an average
A student writes total = 82 + 90 + 77, then average = total / 3, then print('Average: ' + average). 1. Running it stops with TypeError: can only concatenate str (not "float") to str. 2. The message says + was given a string and a float. 3. Fix it with print('Average: ' + str(average)), which shows Average: 83.0. 4. Later the student shortens the code to average = 82 + 90 + 77 / 3. It runs, but prints 197.666..., a logic error. 5. Precedence divides only 77 by 3 before adding. 6. Fix it with parentheses: (82 + 90 + 77) / 3 gives 83.0 again, matching a hand check of 249 ÷ 3.
Common mistakes to avoid
Reading = as a question of equality leads to confusion over statements like x = x + 1; it is an instruction to store. Expecting / to give a whole number trips up loops and counts: 6 / 3 is 2.0, a float. Writing 2 ^ 8 for a power silently gives 10, not 256. Joining text and numbers with + raises a TypeError until you convert with str(). Forgetting precedence turns an average into a logic error. And typing Total when the variable is total produces a NameError, because names are case-sensitive.
Key takeaways
Python 3 is an interpreted language: statements run at the >>> prompt or from a .py script. print() displays values, quotes mark strings, and # starts a comment. Assignment stores the right-hand value under a name, and Python is dynamically typed. Its int grows without overflow, its float is normally an IEEE double, and hex or binary literals are just other spellings of an integer. Use / for division with a float result, // and % for quotient and remainder, ** for powers. Convert types with str(), int() and float(). Bugs come as syntax errors, runtime errors and logic errors.
Flashcards
Flashcard
Carries out a program's statements one at a time
Test your understanding
Question 1 of 5
What does print(17 // 5, 17 % 5) display?
Question 2 of 5
After x = 5 and then x = x * 2 + 1, what is the value of x?
Question 3 of 5
Which line raises a TypeError in Python 3?
Question 4 of 5
After x = 0xFF, what does print(x) display?
Question 5 of 5
average = 82 + 90 + 77 / 3 prints 197.666... instead of 83.0. What is the problem?
