Courseiva
PCAP-31-03Chapter 1 of 17Objective 1.1

Python Basics, Variables, and Core Data Types

Python is a programming language that lets you give instructions to a computer using words and symbols that humans can read. But a computer does not understand concepts like 'a number' or 'text' the way humans do — it needs precise definitions, which is where variables and data types come in. For the PCAP-31-03 exam, you must be able to declare variables correctly and recognise the four fundamental data types every Python program relies on.

12 min read
Beginner
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Python Basics, Variables, and Core Data Types

The Kitchen Measurement Cup Analogy

A kitchen measuring cup is a container that holds a specific amount of ingredient. In baking, the cup itself is the container, but what matters is what you put inside it: flour, sugar, or water. The cup stays the same, but the ingredient changes the recipe.

Your computer's memory is like a giant set of empty measuring cups. Each cup is a memory location that can hold one thing at a time. A variable in Python is like a sticky label you write a name on and stick to a measuring cup. The label says "flour" but right now the cup might actually contain sugar. When the recipe says "add flour", you look at the cup labelled "flour" and use whatever is inside — even if you changed it from flour to sugar five minutes ago.

In Python, the variable name (the label) stays the same, but the value (the ingredient) can change. The type of data — whether it's a number (int or float), a true/false value (bool), or a piece of text (str) — determines how you can use that ingredient. You cannot bake a cake by adding a number of cups of water to a recipe that calls for cups of flour, just as you cannot add a string of text to a mathematical calculation without telling Python to convert it first. The measuring cup analogy makes it concrete: variables are labelled containers, and data types are the rules for what kind of ingredient each container holds.

How It Actually Works

At the heart of every Python program is the idea of storing and manipulating data. A variable is a named location in the computer's memory where you can store a value. Think of it as a box with a label. You create a variable by giving it a name and assigning it a value using the equals sign (=). For example: age = 25. This tells Python to find a memory location, label it 'age', and put the number 25 inside it.

Data types define what kind of data a variable holds and what operations you can perform on it. Python has four built-in core data types that the PCAP-31-03 exam tests heavily:

int (integer): a whole number without a decimal point, like 42, -7, or 1000000. Integers can be positive, negative, or zero. They are used for counting and indexing.

float (floating-point number): a number with a decimal point, like 3.14, -0.001, or 2.0. Floats represent real numbers and are used when you need precision, such as in measurements or scientific calculations.

bool (boolean): a value that is either True or False. Booleans are the result of comparisons (like 5 > 3 gives True) and are used in decision-making, such as in if statements and while loops.

str (string): a sequence of characters enclosed in quotes — either single quotes ('hello') or double quotes ("hello"). Strings are used for text, such as names, messages, or any data that is not numeric.

Python is a dynamically-typed language, which means you do not need to declare the type of a variable when you create it. Python figures it out from the value you assign. For instance, if you write score = 95, Python knows score is an int. If you later write score = "ninety-five", Python changes the type to str. This flexibility is powerful but can lead to errors if you try to combine incompatible types, like adding an int to a string.

Why do data types exist? They exist because the computer stores and processes different kinds of data differently. An integer is stored as a binary number in a fixed amount of space. A float uses a special representation (IEEE 754) that can handle decimals but with limited precision. A boolean is stored as a single bit. A string is stored as a sequence of character codes (typically Unicode). By knowing the type, Python knows how to perform operations correctly. For example, the + operator adds two numbers but concatenates (joins) two strings.

The type() function is your friend. It returns the data type of any value or variable. For example, type(42) returns <class 'int'>. type(3.14) returns <class 'float'>. type(True) returns <class 'bool'>. type('hello') returns <class 'str'>. You can use this to check what type a variable is at any point, which is extremely useful for debugging.

Variable naming rules are part of the exam. Variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot start with a digit. After the first character, they can contain letters, digits, and underscores. They are case-sensitive, so age and Age are different variables. They cannot be the same as Python's reserved keywords (like if, else, for, while, True, False, None, and, or, not, etc.). A good variable name is descriptive and uses lowercase with underscores for multi-word names (snake_case), such as user_score or first_name.

Another important concept is that variables are references to objects in memory. When you assign a variable, you are not copying the value; you are making the variable point to the object that holds the value. This becomes important when you start working with mutable objects (like lists) later, but for the four basic types, they are immutable (cannot be changed after creation). So when you reassign a variable, you are simply pointing it to a new object.

Finally, the exam expects you to understand type conversion (casting). You can convert between types using functions like int(), float(), str(), and bool(). For instance, int("10") converts the string "10" to the integer 10. float("3.14") gives 3.14. str(100) gives the string "100". bool(0) gives False, bool(1) gives True, bool("") gives False, and bool("anything") gives True. These conversions are essential when you read data from a file or user input, which always comes as strings.

The flowchart shows how declaring a variable leads to automatic type detection based on the value, and how the type() function confirms the data type.

Walk-Through

1

Declare a variable

You create a variable by writing a name, an equals sign, and a value. Example: age = 25. This step is how you tell Python to reserve memory for a piece of data. The variable name is a label, and the value is what you store.

2

Choose the data type implicitly

Python figures out the data type from the value you assign. 25 becomes int, 25.0 becomes float, 'hello' becomes str, True becomes bool. You do not need to specify the type explicitly, which is different from many other languages.

3

Check the type with type()

Use the type() function to verify what data type a variable holds. For example: print(type(age)) will show <class 'int'>. This step is vital for debugging and ensuring you are using the correct type in operations.

4

Convert between types when needed

If you need to combine different types, you must convert them first using int(), float(), str(), or bool(). For example: price = '49.99'; total = float(price) * 0.08. Without conversion, adding a string and a number raises a TypeError.

5

Use the variable in expressions

Once declared, you can use the variable in calculations, comparisons, or concatenations. For example: total_price = price + tax. Python applies the operator according to the data types: + adds numbers and concatenates strings.

6

Reassign the variable to a new value

You can change what a variable holds by assigning a new value. For example: score = 95 then later score = 'A+'. This is allowed because Python is dynamically typed. The old value is discarded if no other variable references it.

7

Follow naming conventions and rules

Always use valid variable names: start with a letter or underscore, use only letters, digits, and underscores, and avoid Python keywords. Use snake_case for readability. This step ensures your code runs without syntax errors and is easy for others to read.

What This Looks Like on the Job

An IT professional working in data analysis might need to process a spreadsheet of customer orders. The spreadsheet contains columns for order ID (integer), price (float with two decimals), customer name (string), and whether the order was shipped (yes/no, which maps to boolean).

When they write a Python script to read this data, they first store each row in a variable. The order ID is stored as an int, the price as a float, the customer name as a str, and the shipped status as a bool (True for 'yes', False for 'no'). - They read the price from the spreadsheet. Even though it looks like a number, the data may come in as a string ("49.99"). They must convert it using float("49.99") before performing arithmetic, like calculating tax or discount. - The order ID is used to look up the customer in a database. If it accidentally gets treated as a string during a search, the query might fail or return no results. The professional must ensure the variable type matches the database field type. - The shipped status is a boolean. In the script, they might write: if shipped: send_confirmation_email(). This only works if shipped is a boolean True or False. If the spreadsheet stores 'yes' or 'no', they must convert it first by comparing the string: shipped = (status_string == 'yes'). - When generating a report, they need to format the output. They might combine variables of different types into a single string for printing. For example: print(f"Order {order_id}: {customer_name} paid ${price:.2f}"). This uses an f-string (formatted string literal) that automatically converts non-string variables to strings using their built-in representation. - Debugging type errors is a daily task. A common runtime error is a TypeError when trying to add a number to a string. For instance, total_price = price + tax might work, but total_message = "Total: " + price will crash because you cannot add a string and a number. The professional must convert: total_message = "Total: " + str(price).

In a more advanced scenario, the professional might use type hints (introduced in Python 3.5) to document what type a variable should be. For example: def calculate_discount(price: float, percentage: float) -> float:. This helps other developers (and the programmer) understand the intended types, though Python does not enforce them at runtime.

Finally, when writing automated tests, the professional will use the type() function or isinstance() to verify that functions return the expected data types. This catches bugs early before the code goes to production.

How PCAP-31-03 Actually Tests This

The PCAP-31-03 exam tests data types and variables in several ways. Expect multiple-choice questions that require you to predict the output of code snippets, identify legal variable names, and recognise type conversion behaviour.

Key exam topics:

Variable naming rules: Which of the following is a valid variable name? They will give options like "2nd_place", "_score", "my-var", "class". Remember that names cannot start with a digit, cannot contain hyphens, and cannot be reserved keywords. Underscores are allowed anywhere. "class" is a keyword, so it is invalid.

Type() function: Questions that ask: What is the output of type(3.0)? The answer is <class 'float'>. They test whether you recognise that 3.0 is a float, not an int. Similarly, type(True) is <class 'bool'>.

Implicit type conversion: Python automatically converts some types in operations. For example, 5 + 3.0 results in 8.0 (a float) because int is promoted to float. But 5 + "3" raises a TypeError. They love to test this distinction.

Type casting: Which of the following correctly converts a string to an integer? int("10") works, float("10") gives 10.0, str(10) gives "10", bool("10") gives True. They may ask: what is the value of int(False)? Answer: 0. int(True) gives 1.

Boolean contexts: They test which values are considered falsy: 0, 0.0, "", None, False, empty collections. Every other value is truthy. Questions like: if ["a"]: print("yes") — what happens? Lists with elements are truthy, so it prints "yes".

String operations: They test that + concatenates strings and * repeats them. For example, "ha" * 3 gives "hahaha". They also test that you cannot add a string to an int.

The None value: None is a special type (NoneType). It represents the absence of a value. They test that None is not the same as False or 0. Questions like: print(type(None)) expects <class 'NoneType'>.

Common traps:

Trap: They give a question where a variable is assigned a value, then later reassigned using a different type. You must track the last assignment. For example: x = 5; x = "hello"; print(x) outputs "hello", not 5.

Trap: They ask about integer division. In Python 3, / always returns a float. // returns an integer (floor division). They love to test that 7/2 is 3.5 but 7//2 is 3.

Trap: The modulus operator % gives the remainder. 7 % 2 is 1. They may combine this with negative numbers: -7 % 2 is 1 (the result always has the sign of the divisor).

Trap: The exponent operator . 2 3 is 8. They might test that 2 3 2 is evaluated right-to-left, so it is 2 (3 2) = 2 ** 9 = 512.

To memorise: know the four core types (int, float, bool, str), the type() function, valid naming rules, and the falsy values list. Practice predicting output for short code snippets involving these types.

Key Takeaways

Variables are labelled containers in memory that hold values of a specific data type at any given time.

Python's four core data types are int (whole numbers), float (decimal numbers), bool (True/False), and str (text enclosed in quotes).

You can check a variable's type at any time using the type() function, which returns something like <class 'int'>.

String and number types cannot be directly combined in operations; you must convert one using int(), float(), or str().

Variable names must start with a letter or underscore, cannot contain hyphens or spaces, and cannot be Python keywords like if or for.

Python dynamically determines the type of a variable based on the value assigned, allowing you to reassign a variable to a different type later.

The bool type is a subtype of int, with True equal to 1 and False equal to 0 in numeric contexts.

Type conversion using int(), float(), str(), and bool() is essential when reading user input or data from files, which always comes as strings.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

int

Whole numbers only, e.g., 7, -3, 0

Stored exactly in binary as an integer

Used for counting and indexing

float

Numbers with decimal points, e.g., 7.0, -3.14

Stored as an IEEE 754 floating-point approximation

Used for measurements and scientific calculations

str

A sequence of characters enclosed in quotes

Cannot be used in arithmetic directly

Concatenation uses + operator

int

A whole number without quotes

Can be used in all arithmetic operations

Addition uses + operator to sum values

bool

Only two values: True and False

Used in conditional statements and comparisons

Truthy and falsy values matter for conversion

int (subtype relation)

True equals 1, False equals 0 in numeric contexts

Booleans inherit int methods like bitwise operators

int(True) returns 1, int(False) returns 0

Implicit type conversion

Python automatically converts types in some operations, e.g., int + float gives float

No function call needed

Can lead to unexpected results if not aware

Explicit type conversion (casting)

You manually convert using int(), float(), str(), bool()

Required when mixing incompatible types like string and int

Gives you control over the conversion process

Watch Out for These

Mistake

A variable's type is fixed once you assign it, like in Java or C++.

Correct

Python is dynamically typed, so a variable can be reassigned to a different type at any time. For example, x = 5 then x = 'hello' works fine.

Beginners often come from other languages where variable types are static, so they assume the same rule applies in Python.

Mistake

The string '123' is the same as the integer 123 and can be used interchangeably in arithmetic.

Correct

'123' is a string of characters, not a number. You must convert it using int('123') before doing arithmetic like addition. Adding an int and a string causes a TypeError.

In everyday life, we see '123' written on paper and treat it as a number, so the distinction feels pedantic until you realise computers handle text and numbers completely differently.

Mistake

True and False are special keywords that are not related to any data type.

Correct

True and False are actually instances of the bool data type, which is a subtype of int. True is 1 and False is 0 in numeric contexts.

Beginners rarely think of true/false as 'numbers' because that concept does not exist in natural language.

Mistake

The type() function tells you what the variable's name is.

Correct

type() returns the data type of the value the variable refers to, not the variable's name. For example, x = 10; type(x) returns <class 'int'>.

The word 'type' is ambiguous in English — it could mean 'kind of thing' or 'the specific item'. Beginners naturally misinterpret it as returning the variable's identifier.

Mistake

You cannot use underscores in variable names because they are reserved for special Python functions.

Correct

Underscores are allowed and commonly used in variable names. Stylistically, single leading underscores are used for 'private' by convention, but they are not enforced by the language.

New programmers see things like __init__ or _variable in examples and assume underscores have special meaning that prevents their use in everyday variables.

Mistake

Floats and integers are interchangeable because they both represent numbers.

Correct

They are not interchangeable in all contexts. For example, 7/2 returns 3.5 (a float), but 7//2 returns 3 (an int). Using a float where an int is expected may cause precision issues or type errors.

In math class, 7/2 is a fraction, not a whole number. But in programming, the division operator always returns a float, which surprises people who expect integer division by default.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between int and float in Python?

An int is a whole number without a decimal point, like 5. A float has a decimal point, like 5.0. Python stores them differently: ints are exact, while floats are approximations of real numbers and can have rounding errors.

Can I change a variable's type after I assign it?

Yes, Python is dynamically typed. You can reassign a variable to a different type at any time. For example, x = 10 then x = 'hello' works fine, but the old value is lost.

Why does '2' + 2 give an error in Python?

Because '2' is a string and 2 is an integer. The + operator is overloaded: it adds numbers and concatenates strings, but it does not automatically convert between types. You must use int('2') + 2 to get 4.

What does the type() function return?

The type() function returns the data type of the value you pass to it, as a type object. For example, type(3.14) returns <class 'float'>. It does not return the variable name.

Is True the same as 1 in Python?

True and False are boolean values, but they are actually subclasses of int. In numeric contexts, True behaves like 1 and False like 0. So True + 1 equals 2, but it is not recommended to treat booleans as numbers for clarity.

What are the rules for naming variables in Python?

Variable names must start with a letter or underscore. They can contain letters, digits, and underscores. They cannot start with a digit, cannot contain hyphens or spaces, and cannot be Python reserved keywords like if, else, or for.

Keep going

You've finished Python Basics, Variables, and Core Data Types. Continue through the PCAP-31-03 study guide to build a complete picture of the exam.

Done with this chapter?