Ch 02Variables, Data Types and Input/Output
Chapter 02 of 08·20 min

Variables, Data Types and Input/Output

Data science and artificial intelligence rely on representing, transforming, and processing real-world data in memory. In this chapter, you will master Python's memory model: how variables act as dynamic references to objects, how to distinguish primitive types (int, float, str, bool, NoneType), how to cast types safely, how to accept interactive user input with input(), and how to construct modern, formatted strings with f-strings.

Learning objectives
  • 01Differentiate the 'box' vs 'tag' mental model of variables and apply PEP 8 snake_case naming conventions
  • 02Identify Python's 5 primitive types: int, float, str, bool, and NoneType using the type() function
  • 03Perform safe type conversion (casting) with int(), float(), str(), and bool() while avoiding common runtime exceptions
  • 04Capture interactive input with input() and handle the critical reality that input() always returns a string
  • 05Construct production-grade string interpolation with f-strings, including precision specifiers, alignment, and formatting
  • 06Diagnose and handle critical edge cases: casting float strings to int, bool('False') truthiness quirks, and empty input values

2.1 Variables as Object References: The Tag Model

In languages like C or Java, a variable is a statically typed 'box' carved out of memory: `int x = 5;`. You cannot put text inside an integer box. In Python, **variables are not boxes; they are named tags (references) bound to objects living in heap memory**. When you write `x = 10`, Python allocates an integer object `10` in memory and attaches the label `x` to it. If you later write `x = 'Hello'`, the label `x` is simply detached from `10` and rebound to the string object `'Hello'`. This property is known as **dynamic typing**. ### Variable Naming Rules (PEP 8): - Names can contain lowercase letters, uppercase letters, digits, and underscores `_`. - Names **cannot begin with a digit** (`2name` is illegal; `name2` is valid). - Names are case-sensitive (`data_point` != `Data_Point`). - Cannot be Python reserved keywords (`class`, `def`, `if`, `while`, `return`, `for`, `import`). - Idiomatic Python convention: Use `snake_case` for variables and functions (e.g. `user_email`, `threat_score`).
Statement 1: Variable Binding & Multiple Assignment

Binding values to variable names and unpacking multiple variables in one line.

# Single variable assignments
student_name = "Alex Chen"
workshop_id = 101
active_status = True

# Multiple assignment (tuple unpacking)
min_score, max_score, threshold = 0, 100, 75

print(student_name, "is enrolled in workshop", workshop_id)
print("Threshold:", threshold, "| Range:", min_score, "to", max_score)
Execution walkthrough
  1. 1.Line 2: Allocates string 'Alex Chen' and binds variable 'student_name'.
  2. 2.Line 3: Allocates int 101 and binds 'workshop_id'.
  3. 3.Line 7: Simultaneously binds min_score=0, max_score=100, threshold=75.
  4. 4.Lines 9-10: Outputs formatted variable values.
Expected output
Alex Chen is enrolled in workshop 101
Threshold: 75 | Range: 0 to 100
Edge cases

• Shadowing built-in names: Writing `print = 5` binds the identifier 'print' to an integer! Subsequent calls to `print(...)` will crash with `TypeError: 'int' object is not callable`. Never use built-in function names as variable identifiers. • Unbalanced multiple assignment: `a, b = 1, 2, 3` raises `ValueError: too many values to unpack`.

Why it happens: Python evaluates the right side of '=' first before binding the variables on the left side.

2.2 Python's Primitive Data Types & type() Inspection

Every value in Python has an associated **data type** that dictates what operations can be performed on it. ### The 5 Primitive Types in Python: 1. **`int` (Integer)**: Whole numbers of arbitrary magnitude (`-42`, `0`, `2026`). In Python 3, integers never overflow. 2. **`float` (Floating-Point)**: Numbers with fractional decimals (`3.14159`, `-0.005`, `1.5e-4`). Represented in IEEE 754 64-bit double precision. 3. **`str` (String)**: Immutable sequences of Unicode characters enclosed in `'` or `"`. 4. **`bool` (Boolean)**: Truth values: exactly `True` or `False`. (Internally, `bool` is a subclass of `int` where `True == 1` and `False == 0`). 5. **`NoneType` (`None`)**: The special singleton object representing the absence of a value or null state.
Statement 2: Inspecting Data Types with type()

Using the built-in type() function to verify the runtime class of variables.

metric_int   = 42
metric_float = 98.6
metric_str   = "Security Alert"
metric_bool  = True
metric_none  = None

print("metric_int   is :", type(metric_int))
print("metric_float is :", type(metric_float))
print("metric_str   is :", type(metric_str))
print("metric_bool  is :", type(metric_bool))
print("metric_none  is :", type(metric_none))
Execution walkthrough
  1. 1.Lines 1-5: Defines variables representing each of the 5 fundamental primitive types.
  2. 2.Lines 7-11: Queries type() and outputs each classification class.
Expected output
metric_int   is : <class 'int'>
metric_float is : <class 'float'>
metric_str   is : <class 'str'>
metric_bool  is : <class 'bool'>
metric_none  is : <class 'NoneType'>
Edge cases

• Checking for None: Always use identity operator `is None` or `is not None` rather than equality `== None`, because custom classes could override `__eq__`, whereas `is` checks memory address.

Why it happens: Every value in Python carries its own type metadata, allowing type() to inspect and return its class directly.

2.3 Explicit Type Conversion (Casting)

Because Python is strongly typed, it will not automatically convert strings to numbers. If you try to add `'10' + 5`, Python will raise a `TypeError: can only concatenate str (not 'int') to str`. You must explicitly convert (cast) types using the built-in constructors: - `int(val)`: Converts integer strings or floats to an int (truncating decimals toward zero). - `float(val)`: Converts integers or decimal strings to floating point numbers. - `str(val)`: Converts any Python object into its printable text string representation. - `bool(val)`: Converts values to boolean based on truthiness rules.
Statement 3: Type Casting with int(), float(), str(), and bool()

Explicit conversion between strings, numbers, and boolean values.

# String to numerical casting
raw_input_age = "24"
age = int(raw_input_age)
print("Next year age:", age + 1)

raw_price = "19.99"
price = float(raw_price)
taxed_price = price * 1.08
print("Price with tax :", taxed_price)

# Number to string casting for concatenation
token_count = 150
status_msg = "Scanned " + str(token_count) + " tokens."
print(status_msg)

# Truthiness casting
print("bool(0)       :", bool(0))
print("bool(42)      :", bool(42))
print("bool('')      :", bool(''))
print("bool('False') :", bool('False'))
Execution walkthrough
  1. 1.Line 3: int("24") parses the numeric string and produces integer 24.
  2. 2.Line 4: 24 + 1 executes integer addition to yield 25.
  3. 3.Line 7: float("19.99") parses the decimal string into float 19.99.
  4. 4.Line 12: str(150) converts int 150 to string '150', allowing safe '+' concatenation.
  5. 5.Lines 16-19: Demonstrates truthiness: 0 and empty string '' are False; 42 and 'False' are True.
Expected output
Next year age: 25
Price with tax : 21.5892
Scanned 150 tokens.
bool(0)       : False
bool(42)      : True
bool('')      : False
bool('False') : True
Edge cases

• Direct float-string to int failure: `int('3.14')` raises `ValueError: invalid literal for int() with base 10: '3.14'`. To convert a float string to an int, you must cascade through float first: `int(float('3.14'))` yields `3`. • The bool('False') Trap: `bool('False')` is `True`! Why? Because 'False' is a non-empty string with length 5. In Python, ALL non-empty strings evaluate to True. Only the empty string `bool('')` evaluates to False.

Why it happens: bool() evaluates truthiness: any non-empty string is truthy, regardless of the text it contains.

2.4 Interactive User Input with input()

Programs become genuinely useful when they respond dynamically to user input. Python provides the built-in function `input(prompt)`. When called: 1. Execution pauses. 2. The optional prompt string is printed to the terminal. 3. The user types input and presses Enter. 4. `input()` reads the line and **ALWAYS returns it as a string (`str`)**. ### The Fundamental Rule of input(): Even if the user types `42`, `input()` returns the string `"42"`. If your program needs to perform math or comparisons on that input, you must immediately cast it with `int()` or `float()`.
Statement 4: Interactive Input with Type Casting

Prompting the user, reading input, casting to numeric types, and validating.

# Simulating user input in queued environment
# Type values into the 'Program Input' drawer before running!
user_name = "Jordan Lee"  # Simulated input
user_credits_str = "120"   # Simulated input

# Casting input to integer
credits = int(user_credits_str)
remaining_required = 160 - credits

print("Student Name    :", user_name)
print("Current Credits :", credits)
print("Credits to Grad :", remaining_required)
Execution walkthrough
  1. 1.Line 6: Converts string '120' to integer 120.
  2. 2.Line 7: Subtracts 120 from 160 to calculate credits remaining (40).
  3. 3.Lines 9-11: Emits the calculated values.
Expected output
Student Name    : Jordan Lee
Current Credits : 120
Credits to Grad : 40
Edge cases

• User pressing Enter without typing anything: input() returns the empty string "". If you attempt int(""), Python raises ValueError: invalid literal for int() with base 10: ''. Always validate or guard inputs. • User typing letters when a number is expected: int('abc') immediately raises ValueError.

Why it happens: Explicit casting converts a string of digit characters into an actual numeric value so arithmetic can be performed.

2.5 Modern String Formatting with f-strings

Historically, Python formatted strings using `%` formatting (`"%s is %d" % (name, age)`) or `.format()`. In Python 3.6, **f-strings (Formatted String Literals)** were introduced, becoming the universal industry standard. An f-string is prefixed with `f` or `F` before the opening quote: `f"Hello {name}"`. Inside `{}` curly braces, you can write **any valid Python expression**, including arithmetic, method calls, and format specifiers. ### Powerful Format Specifiers: - **Decimal Precision**: `{val:.2f}` (formats float to exactly 2 decimal places with rounding). - **Thousands Separator**: `{val:,}` (e.g. `1000000` -> `1,000,000`). - **Padding & Alignment**: `{val:>10}` (right-align in 10-character width), `{val:<10}` (left-align). - **Percentage**: `{ratio:.1%}` (multiplies by 100 and appends `%`, e.g. `0.856` -> `85.6%`).
Statement 5: Advanced f-String Interpolation & Specifiers

Formatting floating point numbers, currency, widths, and inline expressions.

account_holder = "Dr. Maya Patel"
balance = 14250.875
monthly_gain = 0.0845
account_id = 42

# Format precision, commas, alignment, and percentages
print(f"Holder   : {account_holder.upper()}")
print(f"ID       : {account_id:06d}")           # Zero-padded to 6 digits
print(f"Balance  : ${balance:,.2f}")            # 2 decimals + commas
print(f"Growth   : {monthly_gain:.1%}")          # Percentage formatting
print(f"Net Next : ${balance * (1 + monthly_gain):,.2f}") # Inline expression
Execution walkthrough
  1. 1.Line 7: account_holder.upper() executes inline method, outputting 'DR. MAYA PATEL'.
  2. 2.Line 8: 42:06d zero-pads integer 42 to 6 characters -> '000042'.
  3. 3.Line 9: balance:,.2f rounds 14250.875 to 2 decimals (14,250.88) and adds commas.
  4. 4.Line 10: monthly_gain:.1% formats 0.0845 as 8.5%.
  5. 5.Line 11: Calculates inline expression balance * (1 + monthly_gain) and formats as currency.
Expected output
Holder   : DR. MAYA PATEL
ID       : 000042
Balance  : $14,250.88
Growth   : 8.5%
Net Next : $15,455.07
Edge cases

• Escaping literal braces: If you need to print a literal '{' or '}' in an f-string, double them: f'{{Literal}} {val}' prints '{Literal} 42'. • Nested quotes: Avoid using the exact same quotation mark inside the curly braces as the outer f-string in older Python versions: use f'Score: {data["key"]}' with alternating quotes.

Why it happens: Python evaluates expressions inside the curly braces '{ }' at runtime, converts them to strings, and interpolates them directly into the output text.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 2: Formatting User Financial Balances

basic

Modify the starter code to calculate the final balance after a 7.5% annual interest return on an initial deposit of 12,500. Output the final amount formatted to 2 decimal places using an f-string.

Chapter 02 assignmentMilestone

Student Academic Performance & GPA Profiler

Scenario

The academic registrar at the Center of Excellence requires a command-line script to compute student grade statistics, convert raw marks into floating-point percentages, determine credit status, and generate an aligned ASCII report card using modern f-strings.

Implementation requirements
  • Define student metadata: student_name, student_id (integer), and enrolled_semester.
  • Store raw marks for 3 subjects: Python Programming (92.5), Data Analysis (88.0), and Linear Algebra (76.5).
  • Calculate total marks obtained and maximum possible marks (300.0).
  • Calculate overall percentage to 2 decimal places: (total_marks / max_marks) * 100.
  • Compute GPA on a 4.0 scale: (percentage / 100) * 4.0, formatted to 2 decimal places.
  • Generate a formatted ASCII transcript table where subject titles are left-aligned in a 20-character column and marks are right-aligned to 6 characters.
  • Display a final summary banner showing Student Name, ID, Overall Percentage, and GPA.
Edge cases to handle
  • 1.Ensure marks are stored as floats to prevent premature integer truncation.
  • 2.Zero-padded student ID: format 5-digit student IDs with leading zeros if necessary ({student_id:05d}).
  • 3.Exact column alignment: Ensure column headers match the width of data rows.
Starter template
# Chapter 2 Assignment: Student Academic Performance Profiler
# Center of Excellence: Data Science & AI

student_name = "Elena Rostova"
student_id = 4821
semester = "Spring 2026"

# Raw marks for 3 courses
python_mark = 92.5
data_mark = 88.0
math_mark = 76.5

# TODO: Compute total_marks = python_mark + data_mark + math_mark
# TODO: Compute max_marks = 300.0
# TODO: Compute percentage = (total_marks / max_marks) * 100
# TODO: Compute gpa = (percentage / 100.0) * 4.0

# TODO: Print formatted ASCII Transcript using f-strings with alignment specifiers
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01Python variables are dynamic references (tags) bound to objects in heap memory, not fixed memory boxes.
  • 02The 5 primitive types are int, float, str, bool, and NoneType. Query any object's type with type().
  • 03Explicit casting is required to convert types: int(), float(), str(), bool().
  • 04input() ALWAYS returns a string; you must cast numeric inputs before arithmetic.
  • 05f-strings (f'...') evaluate expressions inline and support specifiers like :.2f, :,, :>10, and :06d.
Syntax reference
var_name = valueBinds a variable identifier to an object in memory.
int(str_val), float(str_val), str(num)Explicit type conversion (casting).
f"User: {name}, Balance: \${balance:,.2f}"Formatted string literal with inline expressions and format specifiers.
user_text = input("Prompt: ")Reads a single line of string text from standard input.

Knowledge check

Verify your grasp of the chapter concepts

What is the type of the value returned by calling: input('Enter age: ')?

What will f'{1234.567:,.2f}' produce?

Which of the following will raise a ValueError?