Exam objective 2.1 asks you to understand variables and basic data types: integers, floats, strings, booleans. Without variables, every program you wrote would be a one-shot script that could never remember or change any information while it runs. Variables are how your code stores, updates, and retrieves data—the single most fundamental skill for passing PCEP-30-02 and writing any real Python program.
Jump to a section
A simple way to picture Variables and Basic Data Types
A head chef runs a professional kitchen. Before the dinner service starts, the chef prepares by labelling different containers. Each container has a name written on masking tape—'tomato sauce', 'chopped onions', 'sugar', 'butter'. The chef knows that at a moment's notice, she can reach for the 'sugar' container and get exactly the white granules she expects. The container itself is just a vessel; the label tells everyone what is inside.
Now, during service, a waiter calls out an order for spaghetti bolognese. The chef grabs the 'mince' container and uses its contents. Later, she might empty that container and refill it with 'sausage meat' for the next dish. The container stays the same, but the contents change. The chef never puts the actual sugar into her hand and carries it around the kitchen—she uses the labelled container to transport and track the ingredient.
In programming, variables work exactly like those labelled containers. The variable name is the label. The container is a reserved spot in the computer's memory. The ingredient inside is a piece of data. A variable can hold a number (like 42), a piece of text (like 'hello'), or a true/false value. The chef (your program) can look at what is inside, change it, or pass it to another recipe (function). The label never changes, but the ingredient can be swapped out whenever needed. This is how a computer keeps track of information that changes as a program runs.
A variable is a named location in your computer's memory where you store a value. Think of it as a labelled box. You give the box a name (the variable name), and then you put something inside it (the value). In Python, you create a variable by writing its name, an equals sign, and the value you want to store. For example: age = 25. This tells Python to find an empty memory slot, label it 'age', and store the number 25 there. From that point on, whenever you write 'age' in your code, Python will fetch the value 25.
Variables exist because without them, every piece of data in a program would have to be written directly into the code, and the program could never adapt or respond to user input. Variables allow a program to be dynamic—to ask for a user's name and remember it, to count how many times a loop has run, to store the result of a calculation.
Python tracks the type of data inside each variable. A data type defines what kind of value a variable holds and what operations you can perform on it. PCEP-30-02 focuses on four fundamental types:
Integer (int): a whole number with no decimal point. Examples: 42, -7, 0, 100000. You can do maths with integers—add, subtract, multiply, divide—and you can compare them (is one bigger than another?). Integers are used for counting, indexing, and any situation where fractional values don't make sense (you can't have 2.5 people).
Float (float): a number that has a decimal point. Examples: 3.14, -0.5, 2.0, 1.5e6 (which is scientific notation for 1,500,000). Floats are used for measurements, currency (with caution), percentages, and any situation that requires precision after the decimal point. One key difference from integers: floats can lose precision in some calculations because of how computers store them in binary.
String (str): a sequence of characters—letters, numbers, symbols, spaces—enclosed in quotation marks. Examples: 'hello', "Python", '42', 'I am learning!'. Strings can be combined (concatenated) with the + operator, repeated with the * operator, and you can access individual characters using square brackets and an index (like text[0] to get the first character). Strings are how programs handle text: names, addresses, messages, file contents.
Boolean (bool): a value that is either True or False (notice the capital T and F—Python is case-sensitive). Booleans come from comparisons (like 5 > 3 yields True) and are used to control the flow of a program with if statements and while loops. You can combine booleans with logical operators: and, or, not.
You can check the type of any variable using the type() function. For example, type(age) would return <class 'int'>. Python is dynamically typed, meaning a variable can change its type during a program. You can write x = 10 (integer) and later x = 'hello' (string) without any error. This is convenient but can lead to bugs if you're not careful.
A variable name must follow rules: it can only contain letters, digits, and underscores; it cannot start with a digit; it cannot be a Python keyword (like if, else, for, while, True, False, None). Variable names are case-sensitive: score, Score, and SCORE are three different variables. The convention (PEP 8) is to use snake_case: all lowercase with underscores between words, like total_score.
When you assign one variable to another, Python copies the value (for simple types). For example: a = 5; b = a; a = 10 leaves b as 5 because when you ran b = a, Python copied the current value 5 into b. Changing a afterwards doesn't affect b. This is different from compound types like lists, but for the basic data types in this chapter, assignment always copies the value.
Literal values are the raw values you write in your code: 42 is an integer literal, 3.14 is a float literal, 'hello' is a string literal, True is a boolean literal. You assign these literals to variables. Python also supports special number systems: binary (prefix 0b, like 0b1010 for 10), octal (prefix 0o), and hexadecimal (prefix 0x). You won't need to use them for PCEP, but recognising them is helpful.
The input() function returns whatever the user types as a string. If you need to do maths with that input, you must convert it using int() or float(). Forgetting this conversion is one of the most common beginner errors tested on the exam. Similarly, the print() function can output any type, but it converts everything to a string for display.
Finally, the None value is its own type (NoneType). It means 'no value' or 'empty'. It is not zero and not False. Variables are often initialised to None when their real value hasn't been determined yet.
Choose a Variable Name
Pick a descriptive name that follows Python's rules: only letters, digits, and underscores; cannot start with a digit; cannot be a keyword (like if, for, while). For example, 'user_age' is valid, but '2nd_age' is not. The name should tell anyone reading your code what the variable represents.
Assign a Literal Value
Use the equals sign (=) to assign a literal value to your variable. For example: user_age = 25. Python looks up a memory location, stores the integer 25 there, and binds the name 'user_age' to that location. The literal value can be an integer (25), a float (25.0), a string ('twenty-five'), or a boolean (True).
Use the Variable in an Expression
Now that your variable holds a value, you can use it in calculations, comparisons, or string operations. For example: years_to_retirement = 65 - user_age. Python replaces 'user_age' with the value 25, performs the subtraction, and stores the result in a new variable 'years_to_retirement'.
Reassign the Variable
Variables are mutable—you can change the value they hold by assigning a new value: user_age = 26. The old value 25 is lost (unless another variable also pointed to it). This is how programs keep track of changing information, like updating a counter in a loop or processing the next user input.
Check the Type and Convert if Necessary
Use the type() function to verify what data type your variable holds. If you need to perform an operation that requires a different type (like adding a number from user input, which is a string), use int(), float(), or str() to convert it. For example: total = int(input('Enter count: ')) + 5. This step prevents TypeError crashes.
Output the Variable Value
Use the print() function to display the value stored in your variable to the console. print(user_age) will output '26'. The print() function automatically converts the value to its string representation. You can also combine variables with literal text: print('Your age is', user_age).
Imagine you are an IT support analyst at a small insurance company. Your job is to write a script that processes new customer applications. The company receives a CSV file each morning with names, ages, policy types, and premium amounts. You need to extract each row, validate the data, and calculate a discounted premium for certain age groups.
Your first step is to read the CSV file into your Python program. Each row becomes a list of strings. But you need to treat the 'age' column as a number so you can compare it to thresholds (like 'if age > 65, apply a senior discount'). You assign the age string to a variable raw_age = row[2]. Then you convert it: age = int(raw_age). If the conversion fails (someone typed 'thirty' instead of '30'), your program will crash—so you wrap it in a try/except block to handle that gracefully.
Next, you need to store the premium amount. The CSV gives you a string like '145.50'. You use premium = float(raw_premium). Then you can do calculations: discounted = premium * 0.9 for a 10% discount. You store the result in a new variable discounted_premium. Finally, you build a confirmation message using string concatenation: message = 'Dear ' + name + ', your discounted premium is ' + str(discounted_premium) + ' euros.' Notice you must convert discounted_premium (a float) back to a string to join it with other strings.
You also track whether a customer is eligible for a special offer. You create a boolean variable is_eligible = (age > 60 or premium > 200). This boolean will be True or False. Later, you use it in an if statement to decide whether to print the offer line in the email.
During testing, you find a bug: one customer's premium appears as 310.00000000000006 instead of 310.0. This is the floating-point precision issue. You learn to round() the value before storing it: premium = round(float(raw_premium), 2). This keeps your output tidy and avoids confusing call centre staff.
Day to day, you use variables constantly—tracking counters (how many rows processed, how many errors found), storing filenames, holding configuration values (like discount rate = 0.15). You debug by printing variable values at key points. You rename variables when the business rules change (like renaming 'old_discount' to 'senior_discount' to match the new policy document).
Your script works flawlessly for weeks, until a new intern sends a file where the 'age' column has some values as 'N/A' for non-applicants. Your int() conversion crashes. You add a check: if raw_age.isdigit(): age = int(raw_age) else: age = 0. This is real-world variable handling—defensive coding that assumes data will be messy and plans for it using type checking and conditional logic.
The PCEP-30-02 exam tests objective 2.1 through a mix of multiple-choice questions, single-select questions, and drag-and-drop ordering tasks. They want you to demonstrate that you can correctly identify the data type of a literal, predict the outcome of an expression, and spot invalid variable names or illegal type operations.
Trap patterns they love:
Type confusion with division. In Python 3, dividing two integers with a single slash (/) always returns a float, even if the division is exact (like 4 / 2 gives 2.0, not 2). Double slash (//) does integer division and returns an int (truncating toward negative infinity). The exam will present expressions like print(10 / 2) and ask for the output type. The correct answer is float.
Boolean values as integers. True is effectively 1 and False is 0 when used in arithmetic. So True + True equals 2, and False * 100 equals 0. The exam tests this with expressions like print(True + 5). Many beginners think this is an error, but Python allows it.
The type of the modulo operator result. The modulo operator (%) returns the remainder of a division. Its type matches the types of the operands: 10 % 3 gives an integer (1), but 10.0 % 3 gives a float (1.0).
String indexing starts at 0, not 1. A question might ask what 'Hello'[1] returns. The trap is that beginners think it's 'H' (position 1), but it's actually 'e'. Negative indexing also appears: 'Hello'[-1] is 'o'.
In-place operators. +=, -=, *=, /= modify a variable in place. For example: x = 5; x += 3 sets x to 8. The exam may show a sequence of operations and ask for the final value.
Variable name rules. They will give you a list of names and ask which are valid Python variable names. Common traps: '2nd_place' (starts with digit, invalid), 'my-var' (hyphen not allowed, underscore only), 'class' (reserved keyword, invalid), '_private' (valid, underscore is allowed anywhere).
The difference between = (assignment) and == (comparison). They show code like if x = 5: (which is a syntax error in Python) and ask why it fails.
Concatenating incompatible types. 'Hello' + 5 raises a TypeError. The correct approach is 'Hello' + str(5). The exam will test your recognition of this rule.
The input() function always returns a string. If the user types 42, input() returns the string '42', not the integer 42. The exam will show code like age = input(); print(age + 5) and ask what happens (TypeError).
Key definitions to memorise:
int: whole numbers, unlimited magnitude (Python handles big integers automatically).
float: numbers with a decimal part, stored as double-precision floating-point. Can represent values like 1.5e308 but with finite precision (about 15-17 decimal digits).
str: immutable sequence of Unicode characters.
bool: just True and False. Subclass of int.
None: a singleton object of type NoneType representing absence of a value.
You will also see questions asking you to order steps to assign a value to a variable, or to predict what happens when you reassign a variable that was used to define another. The exam rewards understanding the order of operations and the copy-behaviour of simple types.
A variable is a named reference to a memory location that holds a value, and you create it with the assignment operator =.
Python has four basic data types you must know for PCEP-30-02: int (whole numbers), float (decimal numbers), str (text in quotes), and bool (True/False).
The input() function always returns a string, so you must convert it with int() or float() before doing arithmetic.
Division with one slash (/) always returns a float, even if the division is exact, while double slash (//) performs integer division.
True and False behave as 1 and 0 in arithmetic, so True + True equals 2.
Variable names can only contain letters, digits, and underscores, cannot start with a digit, and cannot be a Python reserved keyword.
You cannot concatenate a string with a number directly—use str() to convert the number first.
The type() function returns the data type of any value or variable.
These come up on the exam all the time. Here's how to tell them apart.
int
Whole numbers only, no decimal point.
Literal examples: 42, -7, 0, 100.
Division with // returns int, / returns float.
float
Numbers with a decimal point or scientific notation.
Literal examples: 3.14, -0.5, 2.0, 1e6.
All division operations return float, even with integer operands.
string (str)
Sequence of characters enclosed in quotes.
Can be combined using + (concatenation) but not arithmetic +.
Cannot be used in mathematical expressions without conversion.
integer (int)
Single numeric value without quotes.
Supports arithmetic: +, -, *, //, %, **.
Cannot be concatenated with other strings directly.
= (assignment)
Sets the value of a variable.
Syntax: variable_name = value.
Does not return a value; it's a statement.
== (comparison)
Checks if two values are equal.
Syntax: value1 == value2.
Returns a boolean (True or False); used in conditions.
True / False (bool)
Represents logical truth or falsehood.
In arithmetic, True = 1 and False = 0.
Used in conditions and logical operations.
None (NoneType)
Represents the absence of a value or 'unknown'.
No numeric equivalent; not equal to 0 or empty string.
Used as a placeholder or default for optional values.
input() return value
Always returns a string, even if the user types a number.
Requires explicit conversion with int() or float() for maths.
Value is determined at runtime, not at coding time.
Literal value in code
Type is determined by how you write it (42 is int, '42' is str).
Does not need conversion; usable in arithmetic directly.
Value is fixed in the source code.
Mistake
Variables store their values permanently inside the name itself, like a label on a jar that becomes part of the jar.
Correct
The variable name is just an alias for a memory address. The value lives in memory, and the name points to it. Reassigning the variable changes the pointer, not the label.
Beginners visualise variables as physical tags that absorb the value, rather than as references to a separate storage location.
Mistake
A float with a decimal point that ends in .0 (like 3.0) is actually an integer because it has no fractional part.
Correct
3.0 is still a float in Python. The presence of a decimal point (even if followed by zero) makes it a float type. The only way to get an int is to write a literal without a decimal point and without using any operator that turns it into a float.
In everyday language, '3.0' and '3' are the same number. In Python, they are different objects with different types and different behaviours (division, memory usage).
Mistake
Assigning one variable to another creates a permanent link so that changing either changes both.
Correct
For basic data types (int, float, str, bool), assignment copies the value. Changing the first variable later does not change the second variable. They become independent after the assignment.
This misconception comes from experience with lists and dictionaries (mutable types) where assignment does create a reference. Beginners don't realise that integers and strings behave differently.
Mistake
You can add a number and a string together to get a longer string, because Python will automatically convert the number.
Correct
Python does not automatically convert types in operations. '5' + 5 raises a TypeError. You must explicitly convert using str(), int(), or float(). The only implicit conversion is between int and float (int + float returns float), and bool being a subclass of int.
Some other programming languages (like JavaScript or PHP) do auto-convert, so beginners who have seen any other language expect Python to behave the same way.
Mistake
The value False is the same as None, because both mean 'nothing' or 'empty'.
Correct
False is a boolean value meaning 'not true'. None is a separate sentinel value meaning 'no value assigned yet' or 'absence of a value'. False is equal to 0 in arithmetic; None is not equal to anything except itself. They are different types (bool vs NoneType).
Both appear in contexts where a value is missing or a condition is not met, so beginners blur them into one concept. The exam tests this distinction explicitly.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
This is a floating-point precision issue. Computers store floats in binary, and many decimal fractions (like 0.1) cannot be represented exactly in binary, leading to tiny rounding errors. The result is approximately 0.30000000000000004. For exact decimal arithmetic, use the decimal module, but for PCEP-30-02, just know that it happens and that rounding can help.
No. Using a variable that has not been assigned raises a NameError. Every variable must be created with an assignment before you try to read its value. You can initialise it to None or 0 as a placeholder if you plan to assign the real value later.
There is no difference in Python. Both 'hello' and "hello" are identical string literals. You can use either, but you must be consistent. The only advantage is that if your string contains a single quote character, you can wrap it in double quotes to avoid escaping: "it's" works, while 'it's' causes a syntax error.
Use the type() function: if type(my_var) == int: prints 'It is an integer'. Or use isinstance(): isinstance(my_var, int). The exam tests both approaches. Remember that True and False are instances of bool, which is a subclass of int, so isinstance(True, int) returns True.
Because '5' is a string and 5 is an integer, and Python does not allow mixing types with the + operator unless one is explicitly converted. You must convert the integer to a string with str(5) first, or convert the string to an integer with int('5') before adding them.
The single equals sign (=) is the assignment operator: it stores a value in a variable. The double equals sign (==) is a comparison operator: it checks whether two values are equal and returns True or False. Accidentally using = in an if statement (if x = 5:) causes a SyntaxError.
You've finished Variables and Basic Data Types. Continue through the PCEP-30-02 study guide to build a complete picture of the exam.
Done with this chapter?