Python foundations · Lesson 3 of 3
Variables, values, and basic data types
Use names, expressions, strings, numbers, booleans, and explicit conversions.
Lesson
1. Concept and mental model
Assignment binds a name to an object: count = 3 makes count refer to an integer object. Names should communicate meaning, such as invoice_total, rather than relying on unexplained abbreviations. Python commonly uses snake_case for variables and functions. The built-in types include integers, floating-point numbers, strings, booleans, and None, which represents the absence of a value. Expressions combine values and operators to produce a result.
2. How it works
Strings are immutable sequences of text. Prefer formatted string literals when inserting values into user-facing output: f'Total: {amount:.2f}' formats a number to two decimal places. Convert external input deliberately: input() returns text, so arithmetic requires conversion such as int(...) or float(...). Conversion can fail with ValueError; validate the input or handle that exception instead of assuming every user enters a valid number.
3. Use it safely and effectively
Use type(value) or isinstance(value, ExpectedType) when type inspection is genuinely needed, but do not scatter defensive checks that obscure a clear contract. Python’s bool values are True and False, with capital letters. Use is None when checking for the sentinel None; do not use == as a substitute in that case. Practice by converting a price and quantity, calculating a total, and formatting the result.
4. Syntax reference
price = 19.5
quantity = 3
total = price * quantity
print(f'Total: {total:.2f}')5. Python data types at a glance
intstores whole numbers, such as3.floatstores approximate decimal numbers, such as19.5.strstores text, such as"Python".boolstoresTrueorFalse;Nonerepresents no value.
6. Python built-in data types explained
Numeric types: int, float, complex
Use int for whole numbers, float for approximate decimal values, and complex for numbers with real and imaginary parts. For exact money calculations, consider Decimal or integer cents instead of binary floating-point.
age = 25 # int
price = 19.95 # float
measurement = 2 + 3j # complex
print(type(age).__name__)Boolean: bool
A bool is either True or False. Comparisons and logical expressions produce booleans; bool is a subclass of int, so do not rely on True and False behaving like ordinary numeric values.
is_adult = age >= 18
has_ticket = True
can_enter = is_adult and has_ticket
print(can_enter)Text: str
A str is an immutable sequence of Unicode text. Index and slice it to read parts, and use f-strings to format values. String methods such as strip() return a new string rather than changing the original.
language = 'Python'
print(language.upper())
print(language[0:3])Lists: list
A list is an ordered, mutable collection. It allows duplicate values and can be changed after creation, which makes it useful for a sequence that grows or is edited.
scores = [82, 91, 91]
scores.append(76)
print(scores)Tuples: tuple
A tuple is an ordered collection that cannot be reassigned item by item after creation. It can hold mixed values and is often used for a fixed record or a function returning several values.
point = (10, 20)
x, y = point
print(x, y)Ranges: range
A range represents an arithmetic sequence of integers without storing every item as a list. Its stop value is excluded, which is useful for counted loops.
for number in range(1, 4):
print(number)Dictionaries: dict
A dict maps unique, hashable keys to values. It is mutable and preserves insertion order; use get() or an explicit membership check when a key may be absent.
user = {'name': 'Asha', 'active': True}
print(user.get('city', 'Unknown'))Sets: set and frozenset
A set stores unique hashable values and is useful for membership checks and set operations. A set is mutable; a frozenset is its immutable counterpart. Sets do not provide positional indexing.
skills = {'Python', 'SQL', 'Python'}
required = {'SQL', 'Git'}
print(skills & required)Binary types: bytes, bytearray, memoryview
bytes is an immutable sequence of byte values, bytearray is a mutable byte sequence, and memoryview provides a view into binary data without copying it. These types are common in files and network protocols.
raw = b'ABC' # bytes
mutable = bytearray(raw) # bytearray
view = memoryview(raw) # memoryview
print(raw[0])No value: NoneType
None is the single value of the NoneType type and commonly means a value is missing or not yet set. Compare it with is None rather than a truthiness check.
middle_name = None
if middle_name is None:
print('Not provided')7. Guided walkthrough
Read input as text, convert it to the intended type, and calculate only after conversion succeeds. Choose a type that matches the meaning of the value; for example, use a boolean for a yes/no state and None when a value is absent.
8. Common mistakes to avoid
- Assuming input() returns a number; it always returns a string.
- Using floating-point values for exact currency calculations without considering Decimal or integer cents.
Visual guide
Working with a value
-
Step 01
Read
Receive text or another input value.
-
Step 02
Convert
Validate and convert to the needed type.
-
Step 03
Compute
Use the typed values in an expression.
Code examples
price = 19.5
quantity = 3
total = price * quantity
print(f'Total: {total:.2f}')
Total: 58.50
raw_age = '21'
age = int(raw_age)
print(age >= 18)
True
discount = None
if discount is None:
discount = 0.0
print(discount)
0.0
Key points
- Use names, expressions, strings, numbers, booleans, and explicit conversions.
- Prefer explicit, testable behavior over hidden side effects.
- Validate assumptions at system boundaries and handle failure deliberately.
Check your understanding
Practice
Your learning progress