Skip to content

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 typeDescriptionExamples
IntegerWhole numbers5, -3, 1000
Float / RealDecimal numbers3.14, -0.5, 99.9
StringText (characters in quotes)"Alice", "Hello, world!"
BooleanTrue or False onlyTrue, False
CharA single character'A', '5', '!'

Why data types matter

  1. Storage - an integer uses less memory than a float.
  2. Operations - you can add integers; you concatenate strings.
  3. Validation - checking that age = 25 is 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  # boolean

Type 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

ScopeWhere it is accessibleExample
LocalOnly inside the function it is declared inA variable declared inside def calculate()
GlobalAccessible everywhere in the programA 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_score

Managing variables - best practices

  • Use descriptive names: studentName not s.
  • Use camelCase or snake_case consistently: totalScore or total_score.
  • Initialise variables before use: count = 0 before count = count + 1.
  • Don't use a variable name that is a reserved word (if, while, print, etc.).

Summary

TermMeaning
VariableNamed memory location whose value can change
ConstantNamed value that is set once and never changes
Data typeThe kind of data stored (integer, string, boolean, etc.)
Type castingConverting a value from one data type to another
Local variableOnly accessible inside the function it was declared in
Global variableAccessible throughout the entire program

Test Yourself

Question 1 of 5

What is the key difference between a variable and a constant?

Ad

PassMaven - revision made simple.