Computer Science › Section G · Programming languages › Topic G.2
Traditional concepts: variables, types, and control
Python, C, Java and their relatives look different on the page, but underneath they share the same small set of building blocks. Learn these once, properly, and every new language becomes a matter of new spelling rather than new ideas.
Three kinds of statement
A program in an imperative or object-oriented language is mostly made of three kinds of statement. Declarative statements introduce names, such as the variables that will hold data. Imperative statements describe the steps of the algorithm: compute this, compare that, repeat. Comments are notes for human readers that the translator ignores. A typical program unit declares its data first, then gives the imperative statements that work on it.
Variables and data types
A variable is a name that refers to a stored value, so the programmer never handles raw memory addresses. Its data type says how the bits are interpreted and which operations make sense. In C, a declaration such as int count = 0; fixes the type before the program runs, and the compiler can reject code that misuses it: this is static typing. In Python, count = 0 creates the variable, and the type belongs to the value rather than the name, so it is checked only as the program runs: this is dynamic typing. Both approaches still need the type to know what an operation means.
The primitive types
Most languages provide four basic types. Integers are whole numbers, usually stored in two's complement. Floating-point values, often called float or real, hold numbers with fractional parts, approximately. Characters hold single symbols such as a letter or digit. Booleans hold only true or false. Strings, sequences of characters, hold text. Type matters even for arithmetic: in C, 7 / 2 between two integers gives 3, because integer division discards the remainder, while in Python 3, 7 / 2 gives 3.5 and 7 // 2 gives 3. Floating-point values are approximations, so in Python 0.1 + 0.2 == 0.3 is False.
Arrays and records
A data structure groups values under one name. An array is a block of values of the same type, a homogeneous structure, reached by index. In Python, after scores = [88, 92, 75], scores[0] is 88 and scores[2] is 75, because indexing starts at 0, as it does in C and Java. FORTRAN arrays start at 1 by default, so always check the convention. A record, called a struct in C, is heterogeneous: it groups fields of different types, such as a student's name, age and average, and each field is reached with dot notation, as in student.age. A Python dictionary stores key-value pairs looked up by key: after ages = {"Ana": 15}, ages["Ana"] is 15.
Literals and named constants
A literal is a value written directly in the code, such as 3 or "Monday". Text literals are wrapped in quotation marks so the translator can tell the string "total" from a variable called total. Scattering an unexplained literal such as 0.0725 through a program is poor style: readers cannot tell what it means, and changing it means hunting down every copy. A named constant fixes this: const double TAX_RATE = 0.0725; in C, or a final variable in Java. Python has no enforced constants, so programmers signal one by writing the name in capitals.
Assignment, precedence and overloading
An assignment statement evaluates the expression on the right and stores the result in the variable on the left, so x = x + 1 is a command, not an impossible equation. Python, C and Java write assignment as = and equality testing as ==, while Pascal and Ada write assignment as :=. Precedence rules decide the order of operations: multiplication and division come before addition and subtraction, and parentheses override them. One symbol can mean different operations depending on its operands, which is called overloading: + adds numbers but joins strings, so "ab" + "cd" gives "abcd".
Worked example: evaluating expressions
Predict what Python 3 prints for each expression, then check. Steps: (1) 3 + 4 * 2: multiplication first, 4 * 2 = 8, then 3 + 8 = 11. (2) (3 + 4) * 2: the parentheses come first, so 7 * 2 = 14. (3) 17 // 5 and 17 % 5: floor division gives 3 and the remainder is 2, and indeed 5 × 3 + 2 = 17. (4) 17 / 5: ordinary division always gives a float in Python 3, so 3.4. (5) "ab" * 3: with a string and an integer, * means repetition, giving "ababab". (6) "Total: " + 5: + cannot join a string to an integer, so Python raises a TypeError while running; str(5) converts the number first.
Control statements
Control statements change the order in which statements run. The oldest is goto, a direct copy of the machine's jump instruction, which lets execution leap to any labelled line. Programs full of gotos become tangled and hard to verify, so modern practice, called structured programming, uses statements that wrap a whole branching pattern in one structure. The if-else statement chooses between two paths, and a while loop repeats its body as long as a condition stays true. Conditions combine comparisons with and, or and not, and Python writes an else-if chain as elif. A switch or case statement picks one of several paths from a variable's value; Python 3.10 and later offers match for a similar job.
For loops and comments
For loops come in two main styles.The C-family loop for (int i = 0; i < 3; i++) packs initialisation, test and update into one line and runs with i equal to 0, 1 and 2. Python's for loop instead walks through a collection: for count in range(1, 4): runs with count equal to 1, 2 and 3, because range stops before its second argument. Comments are marked by # in Python, and by // or /* ... */ in C, C++ and Java. A good comment explains why something is done, not what an obvious line already says.
Worked example: tracing a while loop
This Python code counts the digits of a number. Line 1: n = 4096. Line 2: digits = 0. Line 3: while n > 0: and, indented under it, line 4: n = n // 10 and line 5: digits = digits + 1. Trace it, recording the values after each pass. Steps: (1) Pass 1: n becomes 409, digits becomes 1. (2) Pass 2: n is 40, digits is 2. (3) Pass 3: n is 4, digits is 3. (4) Pass 4: n is 0, digits is 4. (5) The test 0 > 0 is false, so the loop ends with digits = 4, correct for 4096. (6) Edge check: for n = 0 the loop never runs and digits stays 0, a case a careful programmer would handle separately.
Common mistakes to avoid
Writing = when you mean ==: in Python, if x = 5: is a syntax error, and in C the same slip compiles but assigns instead of comparing. Forgetting that indexing starts at 0, so the last element of a three-item list is at index 2 and index 3 raises an IndexError. Expecting integer division in C or Python's // to keep the fraction. Comparing floats with == instead of checking that they are close. Writing a while condition that never becomes false, so the loop runs forever. Repeating magic literals instead of naming a constant, and writing comments that merely restate the code.
Key takeaways
Programs combine declarations, imperative statements and comments. Variables name stored values; types decide what operations mean, checked before running in static typing and during running in dynamic typing. Integers, floats, characters and Booleans are the primitive types; arrays group values of one type and records group fields of different types. Named constants beat repeated literals. Assignment stores a value, precedence orders operations, and overloading lets one symbol do different jobs. Structured control statements, if-else, while, switch and for, replace goto.
Flashcards
Flashcard
A name that refers to a stored value
Test your understanding
Question 1 of 5
In Python 3, what does the expression 2 + 10 // 4 * 2 evaluate to?
Question 2 of 5
Why is TAX_RATE = 0.0725, used throughout a program, better than typing 0.0725 each time?
Question 3 of 5
A record holds a name (text), an age (integer) and an average (float). How does it differ from an array?
Question 4 of 5
In Python, after total = 0, the loop for k in range(2, 5): total = total + k runs. What is total?
Question 5 of 5
Which statement about static and dynamic typing is correct?
