Appearance
C1 · Variables & Data Types
Spec reference: Section C - Programming Paradigms
Key idea: Understand how programs store, name, and type data.
Variables and Data Types in Python
Data types
Every variable or constant holds a specific type of data. The type determines what values it can hold and what operations can be performed on it.
| Data type | Description | Examples |
|---|---|---|
| Integer | Whole numbers | 5, -3, 1000 |
| Float / Real | Decimal numbers | 3.14, -0.5, 99.9 |
| String | Text (characters in quotes) | "Alice", "Hello, world!" |
| Boolean | True or False only | True, False |
| Char | A single character | 'A', '5', '!' |
Why data types matter
- Storage - an integer uses less memory than a float.
- Operations - you can add integers; you concatenate strings.
- Validation - checking that
age = 25is an integer prevents errors.
Declaring variables
In some languages (like Java, C#), you must declare the type before using a variable:
java
// Java - explicit type declaration
int score = 0;
String name = "Alice";
boolean isLoggedIn = false;In Python, the type is inferred from the value:
python
# Python - type inferred automatically
score = 0 # integer
name = "Alice" # string
is_logged_in = False # booleanType casting (conversion)
Sometimes you need to convert a value from one type to another:
python
age_string = "25" # This is a string
age_number = int(age_string) # Convert to integer
price = 9.99 # Float
price_text = str(price) # Convert to string: "9.99"Common error
If a user types their age as input, it arrives as a string - even if they type 25. You must convert it: age = int(input("Enter age: ")) before doing arithmetic on it.
Scope: local vs global variables
| Scope | Where it is accessible | Example |
|---|---|---|
| Local | Only inside the function it is declared in | A variable declared inside def calculate() |
| Global | Accessible everywhere in the program | A variable declared at the top of the file |
python
total = 0 # global variable
def add_score(points):
bonus = 5 # local variable - only exists here
return points + bonus
print(total) # works - global
print(bonus) # ERROR - bonus is local to add_scoreManaging variables - best practices
- Use descriptive names:
studentNamenots. - Use camelCase or snake_case consistently:
totalScoreortotal_score. - Initialise variables before use:
count = 0beforecount = count + 1. - Don't use a variable name that is a reserved word (
if,while,print, etc.).
Summary
| Term | Meaning |
|---|---|
| Variable | Named memory location whose value can change |
| Constant | Named value that is set once and never changes |
| Data type | The kind of data stored (integer, string, boolean, etc.) |
| Type casting | Converting a value from one data type to another |
| Local variable | Only accessible inside the function it was declared in |
| Global variable | Accessible throughout the entire program |
Test Yourself
Question 1 of 5
What is the key difference between a variable and a constant?