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.
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.
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#).
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
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.
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)
| Task | Python | C# |
|---|---|---|
| String to int | int("42") | int.Parse("42") or Convert.ToInt32("42") |
| String to float | float("3.14") | double.Parse("3.14") |
| Int to string | str(42) | (42).ToString() |
| Float to int | int(3.9) truncates to 3 | (int)3.9 truncates to 3 |
| Check type | type(x) or isinstance(x, int) | x.GetType() or x is int |
Three Quick Challenges
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);Convert the string "25" to an integer so it can be used in arithmetic:
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?
2. A program does: score = int(input("Enter score: ")). The user types "eighty". What happens?
3. What is the output of: print(type(3.0)) in Python?
4. In C#, what is the difference between const and a normal variable?
5. What does int(3.9) evaluate to in Python?
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"
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.Practice what you have learned
Three levelled worksheets. Download, print and complete offline.