Python Basics — Types, Loops & Functions
The Python foundation every data analyst needs: variables, data structures, loops, functions, and comprehensions — the building blocks of Pandas and NumPy later.
Learning Objectives
- Recognize Python's built-in data types and variables.
- Use lists, tuples, dictionaries, and sets — and know when to use each.
- Explain mutable vs immutable types.
- Write loops (
for/while) and functions. - Write list and dictionary comprehensions.
- Explain the difference between
==andis.
1. Variables and Data Types
Python is dynamically typed — you don't declare a type; you just assign a value.
age = 25 # int
price = 25.5 # float
name = "Aarav" # str
is_active = True # bool
total = None # NoneType (represents "nothing")
| Type | Example | Used for |
|---|---|---|
int | 25 | whole numbers |
float | 25.5 | decimals |
str | "Aarav" | text |
bool | True/False | true/false flags |
NoneType | None | missing / no value |
2. Data Structures — List, Tuple, Dict, Set
| Structure | Syntax | Ordered? | Mutable? | Allows duplicates? |
|---|---|---|---|---|
| List | [1, 2, 3] | Yes | Yes | Yes |
| Tuple | (1, 2, 3) | Yes | No | Yes |
| Dictionary | {"a": 1} | Yes* | Yes | No (keys) |
| Set | {1, 2, 3} | No | Yes | No |
# List — ordered, changeable, allows duplicates
sales = [100, 200, 150, 200]
# Tuple — ordered, unchangeable (immutable)
dimensions = (10, 20)
# Dictionary — key-value pairs
customer = {"name": "Aarav", "city": "Mumbai", "balance": 25000}
# Set — unordered, unique values only
cities = {"Mumbai", "Delhi", "Mumbai"} # → {"Mumbai", "Delhi"}
3. Mutable vs Immutable
Mutable objects can be changed after creation; immutable objects cannot. This is a favourite interview question.
| Mutable | Immutable |
|---|---|
| list, dict, set | int, float, str, tuple, bool |
# Mutable: list can be changed
nums = [1, 2, 3]
nums.append(4) # → [1, 2, 3, 4] (same object, changed)
# Immutable: string/tuple cannot be changed in place
text = "hello"
# text[0] = "H" # → TypeError! strings are immutable
4. Conditionals and Loops
Conditionals
balance = 25000
if balance >= 100000:
label = "High"
elif balance >= 30000:
label = "Medium"
else:
label = "Low"
for loop — iterate over a sequence
for city in ["Mumbai", "Delhi", "Chennai"]:
print(city)
while loop — repeat while a condition is true
count = 0
while count < 3:
print(count)
count += 1
for when you know the collection/count, while
when you're repeating until a condition changes.
5. Functions
Functions package logic into a reusable, named block. They take inputs and return a result.
def categorize(balance):
if balance >= 100000:
return "High"
elif balance >= 30000:
return "Medium"
return "Low"
print(categorize(45000)) # → "Medium"
6. List & Dictionary Comprehensions
Comprehensions build a list or dict in a single, readable line — a Pythonic favorite.
# List comprehension: squares of 0–9
squares = [x**2 for x in range(10)]
# → [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With a condition: even squares only
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Dictionary comprehension
balances = {"Aarav": 25000, "Priya": 120000}
high = {k: v for k, v in balances.items() if v > 50000}
7. Interview Questions (with Model Answers)
The Python basics questions interviewers ask. Self-test before revealing.
IQ1. What are Python's built-in data types?
Model answer: "The main ones are int, float, str, bool, and NoneType for scalars; and list, tuple, dict, and set for collections. Each has a different purpose in data work."
IQ2. What's the difference between a list and a tuple?
Model answer: "Both are ordered sequences, but lists are mutable and tuples are immutable. I use a list when the data changes, and a tuple for a fixed set of values — like a row's fixed fields."
IQ3. What's the difference between a list and a set?
Model answer: "A list is ordered and allows duplicates; a set is unordered and keeps only unique values. I use a set to remove duplicates or test membership quickly."
IQ4. What's the difference between a list and a dictionary?
Model answer: "A list stores values by position (index); a dictionary stores key-value pairs. I use a dictionary when I need fast lookup by a name or ID rather than by position."
IQ5. What are mutable and immutable types? Give examples.
Model answer: "Mutable objects can be changed after creation — lists, dictionaries, sets. Immutable objects can't — ints, floats, strings, tuples, booleans. Trying to change a string in place raises a TypeError."
IQ6. What is a list comprehension, and why use it?
Model answer: "It's a compact way to build a list with a single line of code — like [x**2 for x in range(10)]. It's more readable and often faster than an equivalent for loop."
IQ7. What's the difference between == and is?
Model answer: "== compares values; is compares identity — whether two names point to the same object in memory. For most data work I use ==; is is for identity checks like `x is None`."
IQ8. What's the difference between a for loop and a while loop?
Model answer: "A for loop iterates over a known sequence or range; a while loop repeats as long as a condition is true. I use for when I know the items, while when the loop depends on a changing condition."
IQ9. What is a function, and why use one?
Model answer: "A function is a reusable named block of code that takes inputs and returns a result. I use functions to avoid repetition, keep logic organized, and make code testable."
Hands-On Project: Python Basics in Action
Write Python code for each task. Run it and check the output.
Steps
- Create a list of customer balances:
[25000, 120000, 8000, 95000, 45000, 15000]. - Use a for loop to print each balance.
- Write a function
categorize(balance)that returns "High"/"Medium"/"Low". - Use a list comprehension to build a list of "High" balances only.
- Remove duplicates from a list of cities using a set.
- Build a dictionary mapping customer name → balance, and print only balances over 50000.
View Solution / Walkthrough
# 1. List of balances
balances = [25000, 120000, 8000, 95000, 45000, 15000]
# 2. for loop
for b in balances:
print(b)
# 3. Function
def categorize(balance):
if balance >= 100000:
return "High"
elif balance >= 30000:
return "Medium"
return "Low"
# 4. List comprehension for high balances
high = [b for b in balances if b >= 100000] # → [120000]
# 5. Remove duplicates with a set
cities = ["Mumbai", "Delhi", "Mumbai", "Chennai"]
unique_cities = list(set(cities)) # → unordered unique
# 6. Dictionary + filter
customers = {"Aarav": 25000, "Priya": 120000, "Rahul": 8000}
rich = {k: v for k, v in customers.items() if v > 50000} # → {"Priya": 120000}
Key Takeaways
Lists/tuples/dicts/sets each solve a different storage problem.
Mutable (list/dict/set) can change; immutable (str/tuple/int) cannot.
for = known sequence; while = condition-driven repetition.
Comprehensions build collections in one clean line.
== compares values; is compares identity.
Objective Questions — Test Your Understanding
Q1. Which of the following data types is immutable?
Q2. Which data structure stores unique, unordered values?
Q3. Which data structure stores key-value pairs?
Q4. What does the expression [x**2 for x in range(5)] produce?
Q5. What is the difference between == and is in Python?