Lesson 1 of 10
Programming: Lesson 1

Variables, Constants and Data Types

Every program stores and manipulates data. This lesson covers the fundamental building blocks: the different types of data a computer recognises, how variables store them, and how to convert between types.

50 minutes Python + C# toggle
Language: Saved automatically

When your phone displays "Battery: 73%", that number is stored in memory as an integer. When it displays your name on screen, those characters are stored as a string. When it checks whether Wi-Fi is connected, the answer is stored as a boolean. The same program uses all three types simultaneously - and the computer treats them completely differently at the hardware level. Get the type wrong and the program either crashes or silently produces nonsense.

Think about it: What would happen if a program stored a price like 19.99 as an integer? What about storing someone's age as a string? Write down two bugs that could result from each mistake - then look for them as you work through this lesson.
Terms you need to know
Variable
A named memory location whose value can change while the program runs. Points to a place in RAM.
Constant
A named value that is fixed at the start and cannot change. Makes programs easier to read and maintain.
Data type
The kind of data stored: integer, float, string, boolean or character. Determines what operations are valid.
Integer
A whole number with no decimal point. Examples: -3, 0, 42, 1000.
Float
A number with a decimal point (floating-point). Examples: 3.14, -0.5, 99.9. Called double in C#.
String
A sequence of characters enclosed in quotes. Examples: "hello", "42", "true". The last two are strings, not numbers.
Boolean
Can only be True or False. Used in conditions. Python uses True/False; C# uses true/false (lowercase).
Type casting
Converting a value from one data type to another. For example, turning the string "42" into the integer 42.
The five fundamental types

Every value in a program has a type. The type determines how the value is stored in memory and what you can do with it. You cannot add a number to a string without converting one of them first - attempting it causes a TypeError (Python) or a compile error (C#).

Integer
Python: int
C#: int
score = 95
Float
Python: float
C#: double
price = 4.99
String
Python: str
C#: string
name = "Alice"
Boolean
Python: bool
C#: bool
logged_in = True
Character
Python: str (len 1)
C#: char
grade = 'A'
Key difference: Python vs C#

Python is dynamically typed - you do not declare the type, Python infers it from the value. C# is statically typed - you must declare the type before using a variable. This means C# catches type errors at compile time, while Python catches them at runtime (when the program is already running).

Declaring and assigning variables:

# Python - type is inferred automatically
score = 95              # int
price = 4.99            # float
name = "Alice"         # str
logged_in = True      # bool
grade = 'A'           # str (single character)

# Check the type of any variable
print(type(score))    # outputs: <class 'int'>
// C# - type must be declared explicitly
int score = 95;
double price = 4.99;
string name = "Alice";
bool loggedIn = true;
char grade = 'A';

// C# also supports var (type inferred by compiler)
var age = 17;         // compiler infers int
Exam angle

Examiners often test whether you can identify the correct data type for a given scenario. Remember: age, score, count = integer. Price, temperature, average = float/real. Name, address, postcode = string. Is it raining? Has the user logged in? = boolean. A single letter grade = character.

Fixed values and type conversion

A constant is like a variable that cannot be changed once set. Constants make code more readable (using MAX_SCORE instead of the magic number 100) and easier to maintain (change the value in one place instead of hunting through the whole program).

# Python has no built-in constant keyword
# Convention: use ALL_CAPS to signal "do not change this"
MAX_SCORE = 100
PI = 3.14159
TAX_RATE = 0.20

# Python does NOT enforce this - you can still reassign
# (but you should not, and linters will warn you)
// C# enforces constants with the const keyword
const int MAX_SCORE = 100;
const double PI = 3.14159;
const double TAX_RATE = 0.20;

// Attempting to reassign a const causes a compile error:
// MAX_SCORE = 200; // ERROR: Cannot assign to a constant

Type casting converts a value from one type to another. This is essential when reading input (which always arrives as a string) and when you need a precise float from an integer calculation.

# Python type casting functions
age_str = "17"
age_int = int(age_str)        # "17" becomes 17
age_float = float(age_str)    # "17" becomes 17.0
back_to_str = str(age_int)    # 17 becomes "17"

# Common use: converting user input
score = int(input("Enter score: "))

# Dangerous: this crashes if the string is not a valid number
x = int("hello")   # ValueError: invalid literal for int()
// C# type casting options
string ageStr = "17";
int ageInt = int.Parse(ageStr);          // "17" becomes 17
double ageDouble = double.Parse(ageStr); // "17" becomes 17.0
string backToStr = ageInt.ToString();     // 17 becomes "17"

// Safer alternative: TryParse (does not crash on bad input)
int result;
bool ok = int.TryParse("hello", out result);
// ok = false, result = 0 (no crash)
TaskPythonC#
String to intint("42")int.Parse("42") or Convert.ToInt32("42")
String to floatfloat("3.14")double.Parse("3.14")
Int to stringstr(42)(42).ToString()
Float to intint(3.9) truncates to 3(int)3.9 truncates to 3
Check typetype(x) or isinstance(x, int)x.GetType() or x is int
Type Explorer
Type Converter
Enter a value and click a target type to see the conversion code and result in both languages.
Convert to:
Click a target type above to see the conversion...

Three Quick Challenges

Predict the output

What does this print? (Remember operator precedence: multiplication before subtraction.)

x = 10
y = 3
print(x - y * 2)
int x = 10, y = 3;
Console.WriteLine(x - y * 2);
Fill in the blank

Convert the string "25" to an integer so it can be used in arithmetic:

age = ("25")
int age = int.("25");
Spot the bug

This code crashes with a NameError. What is wrong?

Name = "Alice"
print(name)

Test yourself

1. Which data type is most appropriate for storing a student's age?

Integer is correct - age is a whole number with no decimal part. Float would waste memory and suggest a precision that does not apply. String would prevent arithmetic (you cannot add 1 to a string).

2. A program does: score = int(input("Enter score: ")). The user types "eighty". What happens?

int() can only convert strings that contain a valid whole number like "42". Passing "eighty" raises a ValueError. This is why input validation is important - see Lesson 6 (WHILE loops) for how to handle this properly.

3. What is the output of: print(type(3.0)) in Python?

3.0 has a decimal point, so Python stores it as a float, not an int. The decimal point is the key signal. Note: C# uses the name double (not float) for 64-bit floating-point numbers, while Python just uses float.

4. In C#, what is the difference between const and a normal variable?

const is enforced by the C# compiler - attempting to reassign a const causes a compile error. In Python, ALL_CAPS naming is a convention only (not enforced). Both approaches make programs easier to read and maintain by signalling "this value should not change".

5. What does int(3.9) evaluate to in Python?

int() truncates - it drops the decimal part without rounding. 3.9 becomes 3, not 4. The same applies in C# with (int)3.9. If you want proper rounding, use round() in Python or Math.Round() in C#. This is a common source of off-by-one errors in programs.
Challenge question

A student writes this program to calculate the average of three scores. It runs without errors but always produces the wrong answer. Identify the error and explain precisely why it produces the wrong answer, then write a corrected version.

score1 = input("Score 1: ")
score2 = input("Score 2: ")
score3 = input("Score 3: ")
average = (score1 + score2 + score3) / 3
print("Average:", average)
string score1 = Console.ReadLine();
string score2 = Console.ReadLine();
string score3 = Console.ReadLine();
// This line does NOT compile in C# - cannot divide string by int
// But in Python it runs and produces a string like "607080"
The error: input() always returns a string in Python. When you write score1 + score2 + score3 with strings, Python concatenates them instead of adding numerically. If the user enters 60, 70, 80, the result is the string "607080", not 210. Dividing "607080" by 3 then raises a TypeError in Python 3 (you cannot divide a string by an integer).

Fix: Cast each input to int immediately: score1 = int(input("Score 1: ")). Now + performs addition and / performs division correctly. Average = (60+70+80)/3 = 70.0.
Printable Worksheets

Practice what you have learned

Three levelled worksheets. Download, print and complete offline.

Recall
Data Types and Variables
Label data types, identify errors in declarations and complete code snippets for variable assignment.
Download
Apply
Type Casting Practice
Trace through type conversion chains, predict outputs and fix broken casting code.
Download
Exam Style
Exam-Style Questions
State appropriate data types, identify type errors in given code and write corrected versions with justification.
Download
Lesson 1 - Programming
Variables, Constants and Data Types
Starter activity
Write four values on the board: 42, 3.14, "hello", True. Ask students to guess what each one is and why it matters which type the computer uses. Follow up: "What breaks if you store a price as an integer? What if you store an age as a string?" Use this to motivate why types exist.
Lesson objectives
1
Name and describe the five fundamental data types: integer, float, string, boolean and character.
2
Declare variables and constants correctly in both Python and C#.
3
Identify the appropriate data type for a given real-world scenario.
4
Cast between types using int(), float(), str() and their C# equivalents.
5
Explain what happens when an invalid cast is attempted.
Key vocabulary
Data type
Classification of a value. Determines valid operations and how data is stored in memory.
Type casting
Explicit conversion from one type to another. int("42") = 42, str(42) = "42". Can fail if the value is not convertible.
Static typing (C#)
Type is declared before use and checked at compile time. Catches errors before the program runs.
Dynamic typing (Python)
Type is inferred at runtime from the value. Errors are only caught when that line executes.
Discussion questions
Why does a computer need to distinguish between the integer 42 and the string "42"? What goes wrong if it cannot?
When would a float be wrong for storing money (e.g. 0.1 + 0.2 in Python)? What would you use instead?
Why are constants useful when a program uses the same value (like tax rate) in 20 different places?
Exit tickets
State the most appropriate data type for each: (a) number of students in a class, (b) a student's name, (c) whether the student passed. [3 marks]
What is the output of int(float("3.7")) + 1 in Python? Explain each step. [3 marks]
A program stores age = "16". Write the code to add 1 to age and output "17". [2 marks]
Homework suggestion
Write a program that asks the user for their name, age and height in metres. Store each in the correct data type. Calculate and output: (1) their age in months, (2) whether they are tall enough to ride a rollercoaster (minimum 1.4m), (3) a greeting using their name. Write comments explaining each data type choice.