From the free course Intro to Python Fundamentals on Lykke
Unit 1: Computational Thinking and Variables
Key concepts: Computational thinking (sequence and state) · Data types (Integers, Floats, Booleans, Strings) · Variables · Binary Data
Introduces the basics of how computers interpret sequence and state using data types and variables.
Unit 1: Computational Thinking and Variables
Computational thinking is the foundational cognitive process of formulating a problem and expressing its solution in such a way that a computer—a purely logical, state-driven machine—can effectively carry it out. While often conflated with "learning to code," computational thinking is a broader analytical framework. It involves breaking down complex systems into discrete components, identifying patterns, and abstracting away unnecessary details to create a repeatable sequence of instructions.
In this unit, we explore the dual pillars of digital computation: Sequence and State. We will examine how human-readable information is distilled into binary data, how that data is categorized into primitive types, and how variables serve as the fundamental mechanism for managing information over time.
1.1 The Mechanics of Computational Thinking: Sequence and State
At its core, every computer program is a manipulation of state through a defined sequence of operations. To think computationally is to view the world through these two lenses.
1.1.1 Sequence: The Deterministic Path
A sequence is the specific order in which instructions are executed. Computers are inherently "top-down" processors; they do not possess intuition and cannot skip steps unless explicitly told to do so. A change in the sequence of even a single line of code can fundamentally alter the outcome of a program.
The Principle of Sequentiality: In a synchronous execution environment, instruction $I_{n+1}$ cannot begin until instruction $I_n$ has completed its transformation of the system state.
1.1.2 State: The Snapshot of Memory
State refers to the condition of a system at a specific point in time. In programming, the state is the sum total of all stored values in the computer's memory (RAM). As a program executes its sequence, it modifies the state.
| Concept | Definition | Real-World Analogy |
|---|---|---|
| Sequence | The ordered set of instructions. | A recipe's step-by-step instructions. |
| State | The current values of all variables. | The current temperature and ingredients in the bowl. |
| Transition | The act of moving from one state to another. | The act of mixing the ingredients. |
1.1.3 Why it Matters
Understanding state and sequence is critical for debugging. Most logical errors (bugs) arise because the programmer has an incorrect mental model of the state at a specific step in the sequence. By tracing the state through the sequence, developers can pinpoint exactly where the logic diverges from the intended outcome.
1.2 Binary Data: The Atomic Level of Information
Before we can discuss variables, we must understand the medium they inhabit. Computers do not "know" what a number or a letter is. They operate on physical voltages that we interpret as Binary Data.
1.2.1 Bits, Bytes, and Bases
The fundamental unit of information is the bit (binary digit), representing a choice between two mutually exclusive states: 0 (Off/False) and 1 (On/True).
- Bit: A single 0 or 1.
- Byte: A group of 8 bits. A byte can represent $2^8$ (256) distinct values.
- Word: The natural unit of data used by a particular processor design (typically 32 or 64 bits in modern systems).
1.2.2 The Binary-to-Decimal Derivation
To represent a decimal number in binary, we use a positional notation system where each place value is a power of 2.
$$Value = \sum_{i=0}^{n-1} d_i \times 2^i$$
Where $d$ is the digit (0 or 1) at position $i$.
Example: Converting 1011 to Decimal
- $(1 \times 2^3) = 8$
- $(0 \times 2^2) = 0$
- $(1 \times 2^1) = 2$
- $(1 \times 2^0) = 1$
- Total: $8 + 0 + 2 + 1 = 11$
1.3 Primitive Data Types
While everything is binary at the hardware level, high-level languages like Python provide Data Types—abstractions that tell the computer how to interpret a specific sequence of bits and what operations are valid on that data.
1.3.1 Integers (int)
Integers are whole numbers without a fractional component. In many languages (like C or Java), integers have a fixed size (e.g., 32-bit). Python, however, uses "arbitrary-precision integers," meaning they can grow as large as the available memory allows.
1.3.2 Floating-Point Numbers (float)
Floats represent real numbers (decimals). They follow the IEEE 754 standard, which stores numbers in scientific notation: $Sign \times Fraction \times 2^{Exponent}$.
The Floating-Point Pitfall: Because floats are approximations of real numbers in base-2, some decimal fractions (like 0.1) cannot be represented exactly. This leads to precision errors in long calculations.
1.3.3 Booleans (bool)
Named after George Boole, the Boolean type represents logical truth values: True or False. In memory, these are often stored as a single byte (00000001 for True, 00000000 for False).
1.3.4 Strings (str)
Strings are sequences of characters. To store text, the computer uses an encoding standard like ASCII or UTF-8 to map numbers to symbols. For example, the letter 'A' is mapped to the decimal value 65 (binary 01000001).
| Data Type | Python Keyword | Example | Typical Size |
|---|---|---|---|
| Integer | int |
42 |
Variable (Python) / 4-8 bytes (C) |
| Float | float |
3.14159 |
8 bytes (64-bit) |
| Boolean | bool |
True |
1 byte |
| String | str |
"Hello" |
1 byte per ASCII char + overhead |
1.4 Variables: Naming the State
A variable is a reserved location in the computer's memory used to store a value. It acts as a "label" or "container" for data, allowing the programmer to refer to a value by name rather than by its memory address.
1.4.1 Assignment and Memory
In Python, the assignment operator = does not mean "mathematical equality." It means "evaluate the expression on the right and bind the result to the name on the left."
# Python Implementation: Demonstrating State and Type Dynamics
current_user_count = 150 # Integer assignment
growth_rate = 1.05 # Float assignment
is_active = True # Boolean assignment
system_msg = "Status: OK" # String assignment
# State Transition
# The right side is evaluated first (150 * 1.05 = 157.5)
# Then the name 'current_user_count' is rebound to the new float value.
current_user_count = current_user_count * growth_rate
print(f"{system_msg} | Users: {current_user_count} | Active: {is_active}")
1.4.2 Low-Level Perspective
In lower-level languages like C, we must declare the type explicitly, which tells the compiler exactly how many bytes to allocate on the "stack."
/* C Implementation: Explicit Memory Allocation */
#include <stdio.h>
#include <stdbool.h>
int main() {
int age = 25; // Allocates 4 bytes
double pi = 3.14159; // Allocates 8 bytes
bool is_valid = true; // Allocates 1 byte
// Printing memory addresses to show where the 'state' lives
printf("Value: %d, Address: %p\n", age, (void*)&age);
return 0;
}
1.4.3 Variable Naming Conventions
To maintain readability and prevent syntax errors, variables must follow specific rules:
- Must start with a letter or underscore (
_). - Cannot start with a number.
- Can only contain alphanumeric characters and underscores (
A-z,0-9,_). - Case-sensitive (
Ageandageare different variables). - Avoid Reserved Keywords: Do not name variables
if,while,class, orTrue.
1.5 Arithmetic Operators and Type Casting
Computers perform operations based on the data types involved. This is known as Operator Overloading. For example, the + operator adds two integers but concatenates (joins) two strings.
1.5.1 Standard Operators
| Operator | Name | Description | Example (x=10, y=3) |
|---|---|---|---|
+ |
Addition | Sum of values | 13 |
- |
Subtraction | Difference | 7 |
* |
Multiplication | Product | 30 |
/ |
Division | Quotient (always returns a float) | 3.333... |
// |
Floor Division | Quotient without remainder | 3 |
% |
Modulo | Remainder of division | 1 |
** |
Exponentiation | Power of | 1000 |
1.5.2 Type Casting (Conversion)
Sometimes we need to convert data from one type to another. This is called Type Casting.
- Implicit Casting: Python automatically converts an integer to a float during division.
- Explicit Casting: The programmer manually converts a type using functions like
int(),float(), orstr().
\text{Algorithm: Input Normalization}
\begin{enumerate}
\item \text{Receive input } S \text{ as a String.}
\item \text{Attempt conversion: } N = \text{float}(S)
\item \text{If } N < 0, \text{ set } State = \text{"Error"}
\item \text{Else, calculate } Result = N \times \text{Constant}
\end{enumerate}
1.6 Common Pitfalls and Best Practices
1.6.1 The "Off-by-One" and Precision Errors
Beginners often assume 0.1 + 0.2 == 0.3 will evaluate to True. In reality, due to binary float representation, it evaluates to False (the result is actually 0.30000000000000004).
Solution: When comparing floats, check if the difference is smaller than a tiny threshold (epsilon): abs(a - b) < 0.00001.
1.6.2 Uninitialized Variables
Attempting to use a variable before assigning it a value will result in a NameError. The "state" of that name does not exist yet in the program's namespace.
1.6.3 Type Mismatch
Trying to add a string and an integer (e.g., "Age: " + 25) will cause a TypeError. You must explicitly cast the integer to a string: "Age: " + str(25).
1.7 Summary of the Computational Pipeline
- Input: Data enters the system (often as strings from a keyboard or file).
- Casting: Data is converted into appropriate types (Integers for counts, Floats for measurements).
- Processing: The Sequence of instructions modifies the State using arithmetic and logic.
- Output: The final state is converted back into a human-readable format (Strings) and displayed.
Further Exploration: The Von Neumann Architecture
To truly master Unit 1, one should investigate the Von Neumann Architecture, which describes the physical hardware implementation of sequence and state. It consists of a Central Processing Unit (CPU) that fetches instructions in sequence and a Memory Unit that stores the program's state. This hardware reality is what necessitates the software concepts of variables and data types we have explored here.
Source Materials
Study Intro to Python Fundamentals on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of Intro to Python Fundamentals · Browse more course pages