3. Python Data Types

In Python, every value has a data type that tells the computer what kind of data it is and what operations can be performed on it.
Python automatically detects the data type when you assign a value to a variable (known as dynamic typing).
Understanding fundamental data types—such as integers, floats, strings, Booleans, lists, and dictionaries—is essential for building Python programs.
age = 14          # Integer (int)
height = 165.5    # Floating-point number (float)
name = "Alex"     # String (str)
is_student = True # Boolean (bool)

# Check the data type of a variable using type()
print(type(age))  # Output: <class 'int'>

3.1. Basic Data Types (int, float, str, bool)

Python’s primary built-in primitive data types represent simple values:

  • Integers (int): Whole numbers without decimals (e.g., 10, -5, 0). Used for counting discrete items.

  • Floats (float): Numbers with a decimal point (e.g., 3.14, -0.5, 10.0). Used for precise measurements.

  • Strings (str): Sequences of text characters enclosed in quotes (e.g., "Hello", 'Python').

  • Booleans (bool): Conditional truth values that can only be either True or False.

  • The type() Function: Call type(variable) to inspect the data type of any value.

score = 100         # int
price = 19.99       # float
greeting = "Hi!"    # str
game_over = False   # bool

print(type(price))     # Output: <class 'float'>
print(type(game_over)) # Output: <class 'bool'>

3.1.1. Quiz: Basic Data Types

3.1.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
False
float
int
str
type()

1. Whole numbers without decimal points belong to the Drop here data type.
2. Numbers containing a decimal point belong to the Drop here data type.
3. Text enclosed in quotation marks belongs to the Drop here data type.
4. A Boolean variable can only hold the value `True` or Drop here.
5. You can inspect the data type of a value in Python using the Drop here function.

3.1.1.2. Code Ordering Examples

Example 1: Assign different basic data types to variables and print their types.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(type(player_score))
☰
player_score = 250
☰
print(type(player_name))
☰
player_name = "Sam"

Example 2: Declare a float variable for price and print a summary.

Drag and drop lines into the correct order and click to adjust indentation:
☰
price = 12.50
☰
print(f"The {item_name} costs ${price}")
☰
item_name = "Book"

Example 3: Check a Boolean flag in a program workflow.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(is_logged_in)
☰
is_logged_in = True
☰
print(type(is_logged_in))

3.1.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which data type is assigned to the value 42?

Correct! Whole numbers without decimal points are integers (int).

Incorrect. Floats contain decimal points.

Incorrect. Strings are enclosed in quotation marks.

Incorrect. Booleans are True or False.

What data type does "123" belong to in Python?

Correct! Any value enclosed in quotation marks is treated as a string (str).

Incorrect. Quotes convert numeric characters into a text string.

Incorrect. Quotes make it a string, not a float.

Incorrect. It is surrounded by quotes, making it a string.

What does type(3.14) return in Python?

Correct! 3.14 contains a decimal point, classifying it as a float.

Incorrect. 3.14 has a decimal point, so it is not an integer.

Incorrect. Unquoted numbers are numeric types, not strings.

Incorrect. 3.14 is a floating-point number.

Which of the following values belongs to the bool data type?

Correct! True and False (capitalized without quotes) are Booleans.

Incorrect. Quoted text forms a string literal (str).

Incorrect. 1.0 is a float.

Incorrect. Quoted text is a string.

How does Python determine the data type of a variable during assignment?

Correct! Python infers types automatically without explicit declaration.

Incorrect. Python uses dynamic typing.

Incorrect. Python evaluates value representations deterministically.

Incorrect. Python supports multiple distinct data types.

What is the data type of 0 in Python?

Correct! Zero without a decimal point is an integer.

Incorrect. 0.0 would be a float, but 0 is an integer.

Incorrect. While 0 evaluates as falsy, its type is int.

Incorrect. Unquoted 0 is an integer.

Which function returns the data type of an object in Python?

Correct! The built-in type() function reports object classifications.

Incorrect. typeof is JavaScript syntax, not Python.

Incorrect. No check_type() built-in exists in Python.

Incorrect. Python uses type().

What is the data type of the result of 10 / 2 in Python 3?

Correct! Division / always returns a float in Python 3 (5.0).

Incorrect. Standard division yields float output even for exact divisions.

Incorrect. Arithmetic operations output numeric types.

Incorrect. Math division returns numbers.

Which of the following is a valid floating-point number?

Correct! Negative numbers with decimal points are valid floats.

Incorrect. Surrounded by quotes, making it a string.

Incorrect. Whole numbers without decimals are ints.

Incorrect. True is a Boolean.

What happens when you enclose a Boolean value in quotation marks like "False"?

Correct! Placing quotes around any value transforms it into a string.

Incorrect. Quotation marks define string literals.

Incorrect. “False” is a valid string literal.

Incorrect. String quotes prevent numeric conversion.

Question 1 of 0

3.2. Collection Data Types (list, tuple, dict, set)

When storing multiple pieces of data together, Python provides collection data types:

  • Lists (list): Ordered, mutable (changeable) sequences enclosed in square brackets [] (e.g., [1, 2, 3]).

  • Tuples (tuple): Ordered, immutable (unchangeable) sequences enclosed in parentheses () (e.g., (10, 20)).

  • Dictionaries (dict): Unordered mappings of key-value pairs enclosed in curly braces {} (e.g., {"name": "Alex"}).

  • Sets (set): Unordered collections of unique values enclosed in curly braces {} (e.g., {1, 2, 3}).

fruits = ["apple", "banana", "cherry"]  # list
coordinates = (10.0, 20.0)             # tuple
user = {"name": "Taylor", "age": 14}   # dict
unique_ids = {101, 102, 103}            # set

print(type(fruits))  # Output: <class 'list'>
print(type(user))    # Output: <class 'dict'>

3.2.1. Quiz: Collection Data Types

3.2.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
immutable
key-value
parentheses
square
unique

1. Lists are defined using Drop here brackets `[]`.
2. Tuples are defined using Drop here `()`.
3. Dictionaries store data as Drop here pairs inside curly braces `{}`.
4. Sets contain only Drop here values and ignore duplicates.
5. Unlike lists, tuples are Drop here and cannot be modified after creation.

3.2.1.2. Code Ordering Examples

Example 1: Create and inspect a list of student names.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(type(students))
☰
print(students[0])
☰
students = ["Alex", "Jordan", "Taylor"]

Example 2: Construct a dictionary and look up a value by key.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(profile["username"])
☰
print(type(profile))
☰
profile = {"username": "gamer1", "score": 900}

Example 3: Define a tuple representing GPS coordinates.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(lat_long[0])
☰
lat_long = (-37.81, 144.96)
☰
print(type(lat_long))

3.2.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which pair of brackets is used to create a Python list?

Correct! Lists use square brackets [].

Incorrect. Parentheses create tuples.

Incorrect. Curly braces create dictionaries or sets.

Incorrect. Angle brackets are comparison operators.

What key characteristic distinguishes a tuple from a list?

Correct! Tuples cannot be modified after instantiation.

Incorrect. Both can hold any data type.

Incorrect. Tuples use parentheses ().

Incorrect. Lists permit duplicate elements.

What data type is represented by {"a": 1, "b": 2}?

Correct! Key-value pairs inside curly braces form a dictionary (dict).

Incorrect. Sets contain individual elements without key values.

Incorrect. Lists use square brackets and single values.

Incorrect. Tuples use parentheses and sequence items.

What happens when you add a duplicate item to a Python set (e.g., {1, 2, 2, 3})?

Correct! Sets only preserve unique elements.

Incorrect. Adding duplicates is handled silently by ignoring them.

Incorrect. Duplicate elements are ignored without errors.

Incorrect. Object type remains a set.

Which of the following is a valid tuple definition?

Correct! Uses parentheses enclosing comma-separated values.

Incorrect. Square brackets define a list.

Incorrect. Curly braces without key-value colons define a set.

Incorrect. Explicit parentheses are preferred for standard tuple definition.

Given nums = [1, 2, 3], what does type(nums) print?

Correct! nums is a list defined with square brackets.

Incorrect. Defined with [], not ().

Incorrect. Defined with [], not {}.

Incorrect. Defined with [], not key-value {}.

Which collection type stores key-value pairs?

Correct! Dictionaries map key identifiers to stored values.

Incorrect. Lists store ordered sequence values by numerical index.

Incorrect. Tuples store ordered sequence values.

Incorrect. Sets store unique individual elements.

Which collection type is created using my_data = {10, 20, 30}?

Correct! Curly braces containing single values create a set.

Incorrect. Dictionaries require key-value pairs separated by colons (e.g., {“k”: “v”}).

Incorrect. Lists use square brackets [].

Incorrect. Tuples use parentheses ().

Can a single Python list contain items of different data types (e.g., integers, strings, and Booleans)?

Correct! Python collections accept heterogeneous data types.

Incorrect. Python lists are heterogeneous containers.

Incorrect. Any data type can be mixed directly.

Incorrect. Mixed types inside lists are fully supported.

Given person = {"name": "Eva"}, how do you access the value "Eva"?

Correct! Dictionary values are accessed using key names inside square brackets.

Incorrect. Dictionaries are indexed by keys, not positional indices.

Incorrect. Key indexing uses bracket notation person[“name”].

Incorrect. Accessing keys uses square brackets, not parentheses.

Question 1 of 0

3.3. Type Conversion (Casting)

Python allows you to convert values from one data type to another using built-in conversion functions:

  • int(): Converts compatible values (like floats or string numbers) to integers (truncates decimals).

  • float(): Converts integers or valid numeric strings into floating-point numbers.

  • str(): Converts any data type into its string representation.

  • bool(): Converts values to Booleans. Non-zero numbers and non-empty strings convert to True; 0, "", and None convert to False.

num_str = "100"
num_int = int(num_str)    # Converts string "100" to integer 100
print(num_int + 50)       # Output: 150

pi_float = 3.99
pi_int = int(pi_float)    # Truncates decimal part -> 3
print(pi_int)             # Output: 3

text_score = str(95)      # Converts integer 95 to string "95"
print("Score: " + text_score) # Output: Score: 95

3.3.1. Quiz: Type Conversion (Casting)

3.3.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
5
False
float()
str()
type casting

1. Converting a value from one data type to another is called Drop here.
2. The function `int(5.8)` truncates the decimal part and returns Drop here.
3. To convert an integer to a float, use the Drop here function.
4. Converting an empty string `""` using `bool("")` yields Drop here.
5. The function Drop here converts any data type into string format.

3.3.1.2. Code Ordering Examples

Example 1: Convert user string input into an integer for math calculations.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(f"Next year you will be {next_year}")
☰
next_year = age + 1
☰
age = int(age_input)
☰
age_input = "15"

Example 2: Convert an integer score to a string for concatenation.

Drag and drop lines into the correct order and click to adjust indentation:
☰
msg = "Your final score is " + str(score)
☰
print(msg)
☰
score = 85

Example 3: Convert a float price to an integer representation.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(dollars_only)
☰
total_price = 19.95
☰
dollars_only = int(total_price)

3.3.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What is the output of int(7.9) in Python?

Correct! int() truncates the decimal portion completely without rounding up.

Incorrect. int() drops decimals without rounding up.

Incorrect. int() removes the decimal component.

Incorrect. Floating numbers convert cleanly to int.

What happens when you run int("hello")?

Correct! Non-numeric text strings cannot be parsed into integers.

Incorrect. Python throws a ValueError rather than defaulting to 0.

Incorrect. An exception is raised.

Incorrect. Use len() to check string length.

What does float(5) evaluate to?

Correct! Converting integer 5 to float appends decimal precision .0.

Incorrect. Floats always print with a decimal point.

Incorrect. Converts to numeric float, not string.

Incorrect. Integer to float conversion is valid.

What does bool("") (converting an empty string) evaluate to?

Correct! Empty collections and empty strings convert to Boolean False.

Incorrect. Only non-empty strings evaluate as True.

Incorrect. bool() strictly returns True or False.

Incorrect. Empty string conversion is valid.

Which statement about str(100) is TRUE?

Correct! str() wraps numeric values into string representation.

Incorrect. Performing string conversion does not execute math.

Incorrect. Standard type casting operation.

Incorrect. Result data type is str.

What is output by bool(42)?

Correct! Any non-zero number converts to Boolean True.

Incorrect. Only 0 converts to False among numbers.

Incorrect. bool() converts output to Boolean type.

Incorrect. Non-zero integers convert cleanly.

Given x = "10" and y = "20", what does x + y produce?

Correct! Adding two strings concatenates them together rather than performing math.

Incorrect. Values are strings, so concatenation occurs instead of addition.

Incorrect. String addition concatenates characters.

Incorrect. String concatenation is valid syntax.

How can you perform mathematical addition on x = "10" and y = "20"?

Correct! Cast both strings to integers prior to adding them.

Incorrect. Concatenates strings “1020” first.

Incorrect. Concatenates first then casts to float 1020.0.

Incorrect. Strings do not possess an .add() method.

What is the result of str(True)?

Correct! Converts Boolean value True into string literal “True”.

Incorrect. Type transforms to string str.

Incorrect. Int casting int(True) gives 1, but str(True) gives “True”.

Incorrect. Valid type conversion.

What is output by int(True) and int(False) in Python?

Correct! In Python, Booleans inherit from integers where True converts to 1 and False to 0.

Incorrect. int() casts values to integer representation.

Incorrect. True maps to 1, False maps to 0.

Incorrect. Boolean to integer conversion is supported natively.

Question 1 of 0