Python 3.12+ Python Fundamentals Data Analytics Core

Python Variables & Data Types Masterclass

Master Python's foundational building blocks: object references, dynamic typing, core built-in data types (int, float, bool, str, NoneType), type inspection with type(), casting, and string vs numeric calculation pitfalls.

Read Time: 12 mins
Verified Source: Official Python 3 Documentation
Interactive Labs: 6 Live Coding Workbenches
1

1. What is a Variable?

In Python, a variable is a symbolic name (tag) that references an object in memory.

# Variable Assignment in Python
name = "Alex"
age = 25
salary = 50000
🧠 Python Object Reference Model in Memory

Unlike some languages where variables are fixed "boxes" storing a specific type, Python creates an object in memory and binds the name tag to it using the = assignment operator:

name references
"Alex"
str object
age references
25
int object
salary references
50000
int object
2

2. 🔥 Python is Dynamically Typed

Python is dynamically typed. You do not declare a data type beforehand (e.g., no int x = 10;). Python automatically inspects the assigned value at runtime.

Current Object Type: int
# Re-binding variable x to a different data type
x = 10
type(x)  # Returns: <class 'int'>
Dynamic Typing Takeaway: The same name x simply pointed to a different object in memory. In statically typed languages (like C++ or Java), reassigning a string to an integer variable would cause a compile error.
3

3. 🔥 Core Built-in Data Types

Every value you analyze in Python belongs to a specific built-in type:

Type NameCategoryExampleData Analytics Meaning
intInteger (Whole Number)age = 25Customer count, quantity sold, user IDs
floatFloating-Point (Decimal)price = 99.99Currency, percentages, conversion rates
complexComplex Numberz = 2 + 3jSignal processing & advanced engineering
boolBoolean (True / False)is_active = TrueCustomer churned flag, filter conditions
strString (Text Sequence)name = "Alex"Customer names, product SKUs, categories
NoneTypeNull / Absence of Valueresult = NoneMissing data, unpopulated database fields
4

4. 🔥 Live Lab: Identify the Data Type

Task: Match each variable to its correct Python data type. Pay special attention to the difference between 25 and "25":

x = 25
y = 25.5
z = "25"
a = True
b = None
5

5. 🔥 The type() Function

Python provides the built-in type() function to inspect the exact data type of any value or variable:

# Interactive Python REPL
>>> type(age)
<class 'int'>
6

6. 🔥 Live Lab: Data Type Investigation

In real-world data analytics (e.g. reading CSV files with Pandas), columns often load with unexpected types. Inspect this sample record:

FieldSample ValueVisual AppearancePython TypeCalculations Allowed?
customer_id"1094"Looks like numberstr❌ No (Text only)
order_total249.99Decimalfloat✅ Yes (Math enabled)
items_purchased3Whole numberint✅ Yes (Math enabled)
7

7. Reassigning Variables

Variables can be reassigned new values at any time during execution:

score = 80
score = 95
print(score)  # Output: 95

The name score is simply rebound to the new integer object 95.

8

8. Multiple Assignment

Python allows clean, one-line assignments for multiple variables:

# 1. Multiple distinct values
x, y, z = 10, 20, 30

# 2. Same value to multiple variables
x = y = z = 0
9

9. Type Conversion (Casting)

Convert values between types using Python's built-in constructor functions:

int()int("25") ➔ 25

Converts text digits to integer

float()float("99.50") ➔ 99.5

Converts text decimals to float

str()str(100) ➔ "100"

Converts any value to text string

bool()bool(1) ➔ True, bool(0) ➔ False

Converts truthy/falsy values

10

10. 🔥 Live Lab: Converting Raw Dataset Values

Suppose an API returns all numbers as text strings: sales = "50000", quantity = "10", price = "99.50":

Status: Raw Text Strings
# Raw API Ingestion
sales = "50000"
quantity = "10"
price = "99.50"

# Attempting calculation directly on strings:
total_val = quantity * price  # ❌ TypeError: can't multiply sequence by non-int of type 'str'
11

11. 🔥 Common Type Confusion (Strong Typing)

Python is strongly typed at runtime. It will never silently guess whether you intended numeric addition or text concatenation:

>>> 10 + 20
30  # Integer Addition
12

12. Variable Naming Rules (PEP 8)

Follow official Python identifier rules and the PEP 8 style guide:

✅ Valid Variable Names
  • age = 25
  • employee_name = "Amit" (snake_case)
  • total_sales_2026 = 50000
  • _is_calculated = True
❌ Invalid Names (SyntaxError)
  • 2name (Cannot start with a digit)
  • employee-name (Hyphens parsed as subtraction)
  • class or for (Reserved Python keywords)
  • total sales (Spaces not allowed)
13

13. Good Naming Practices for Analytics

Self-documenting code prevents analytical mistakes. Prefer meaningful names over cryptic single letters:

Poor / Ambiguous NameProfessional Data Analytics NameWhy It Matters
x = 50000total_sales = 50000Immediately reveals business metric
n = 1420customer_count = 1420Clarifies count population
avg = 65000.0average_salary = 65000.0Prevents mixing up averages
14

14. Mini Data-Analytics Practical Example

Connecting variables, types, and basic arithmetic in a realistic order invoicing script:

product = "Laptop"        # str
price = 60000           # int
quantity = 3             # int
discount = 0.10           # float (10% discount)

subtotal = price * quantity                 # 180,000 (int)
discount_val = subtotal * discount          # 18,000 (float)
final_total = subtotal - discount_val       # 162,000 (float)
Calculated Invoice: Product: Laptop | Subtotal: $180,000 | Discount (10%): -$18,000 | Final Amount: $162,000
15

15. 🔥 Final Interactive Challenge

Task: You are given an ingested raw customer record where all fields were imported as strings. Rectify the data types:

# Ingested Raw Record:
employee_name = "Rahul"     # Target: str (Keep as text)
age = "28"                # Target: int
salary = "55000.50"          # Target: float
is_active = "True"           # Target: bool

# Click "Execute Data Cleaning Code" to rectify the types!
16

16. Common Mistakes & Traps

1. Confusing "25" with 25

Quoted numbers are strings. Running "25" + "25" results in "2525" instead of 50.

2. Starting Names with Digits

1st_quarter throws a SyntaxError. Use quarter_1 instead.

3. Case-Sensitivity Trap

total_sales and Total_Sales are two completely separate variables in Python.

17

17. Assessment Certification Quiz

Verify your understanding of variables, dynamic typing, built-in types, and type conversions:

TEST YOUR KNOWLEDGE

Python Variables & Data Types Certification Quiz

Answer all 5 questions to test your practical mastery of Python 3 variables and data types.

Question 1 of 5Current Score: 0 / 0
Q1

1. In Python, what is a variable fundamentally?