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.
- 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
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)- 1.Line 2: Allocates string 'Alex Chen' and binds variable 'student_name'.
- 2.Line 3: Allocates int 101 and binds 'workshop_id'.
- 3.Line 7: Simultaneously binds min_score=0, max_score=100, threshold=75.
- 4.Lines 9-10: Outputs formatted variable values.
Alex Chen is enrolled in workshop 101 Threshold: 75 | Range: 0 to 100
• 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
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))- 1.Lines 1-5: Defines variables representing each of the 5 fundamental primitive types.
- 2.Lines 7-11: Queries type() and outputs each classification class.
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'>
• 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)
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'))- 1.Line 3: int("24") parses the numeric string and produces integer 24.
- 2.Line 4: 24 + 1 executes integer addition to yield 25.
- 3.Line 7: float("19.99") parses the decimal string into float 19.99.
- 4.Line 12: str(150) converts int 150 to string '150', allowing safe '+' concatenation.
- 5.Lines 16-19: Demonstrates truthiness: 0 and empty string '' are False; 42 and 'False' are True.
Next year age: 25
Price with tax : 21.5892
Scanned 150 tokens.
bool(0) : False
bool(42) : True
bool('') : False
bool('False') : True• 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()
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)- 1.Line 6: Converts string '120' to integer 120.
- 2.Line 7: Subtracts 120 from 160 to calculate credits remaining (40).
- 3.Lines 9-11: Emits the calculated values.
Student Name : Jordan Lee Current Credits : 120 Credits to Grad : 40
• 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
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- 1.Line 7: account_holder.upper() executes inline method, outputting 'DR. MAYA PATEL'.
- 2.Line 8: 42:06d zero-pads integer 42 to 6 characters -> '000042'.
- 3.Line 9: balance:,.2f rounds 14250.875 to 2 decimals (14,250.88) and adds commas.
- 4.Line 10: monthly_gain:.1% formats 0.0845 as 8.5%.
- 5.Line 11: Calculates inline expression balance * (1 + monthly_gain) and formats as currency.
Holder : DR. MAYA PATEL ID : 000042 Balance : $14,250.88 Growth : 8.5% Net Next : $15,455.07
• 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
basicModify 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.
Student Academic Performance & GPA Profiler
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.
- 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.
- 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.
# 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
Chapter summary
Key concepts and syntax cards for review
- 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.
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?