Python Fundamentals & Data Structures I
From the csc curriculum
Python Fundamentals & Data Structures I
TL;DR
Python is a versatile programming language that uses basic building blocks like variables, data types, and control flow to create programs. Understanding common data structures like lists, tuples, and dictionaries is crucial for storing and organizing information effectively. You'll learn how to manipulate these structures and make decisions in your code.
1. The Mental Model
Think of Python as a set of instructions you give to a computer. These instructions involve storing pieces of information (data) and then telling the computer what to do with that data, step by step. It's like writing a recipe, where ingredients are data and steps are instructions.
2. The Core Material
Variables and Data Types

Photo by Markus Spiske on Pexels
Variables are like labeled boxes where you store values. You give the box a name, and then you put something inside it. Python automatically figures out what kind of data you're putting in, which is its data type.
Here are some fundamental data types you'll use constantly:
- Integers (
int): Whole numbers (e.g.,5,-100). - Floats (
float): Numbers with decimal points (e.g.,3.14,-0.5). - Strings (
str): Text, enclosed in single or double quotes (e.g.,"hello",'Python'). - Booleans (
bool): RepresentsTrueorFalse. Used for logical operations.
# Assigning values to variables
age = 30 # int
pi_value = 3.14159 # float
name = "Alice" # str
is_student = True # bool
print(type(age))
print(type(pi_value))
print(type(name))
print(type(is_student))
Operators
Operators perform actions on values and variables.
- Arithmetic Operators:
+(addition),-(subtraction),*(multiplication),/(division),**(exponentiation),%(modulo - remainder),//(floor division - whole number result). - Comparison Operators:
==(equal to),!=(not equal to),<(less than),>(greater than),<=(less than or equal to),>=(greater than or equal to). These returnTrueorFalse. - Logical Operators:
and,or,not. Combine boolean expressions.
x = 10
y = 3
print(x + y) # 13
print(x / y) # 3.333...
print(x % y) # 1 (remainder of 10 / 3)
print(x > y) # True
print(x == 10 and y == 3) # True
Control Flow: if, elif, else

Photo by Jan van der Wolf on Pexels
Control flow statements allow your program to make decisions. An if statement executes code only if a condition is True. elif (else if) checks another condition if the previous one was False. else runs if all previous conditions were False.
temperature = 25
if temperature > 30:
print("It's hot outside!")
elif temperature > 20: # This runs if temperature is not > 30, but is > 20
print("It's a pleasant day.")
else: # This runs if temperature is not > 30 and not > 20
print("It's a bit chilly.")
Data Structures: Lists, Tuples, Dictionaries

Photo by freestocks.org on Pexels
Data structures are ways to organize and store collections of data.
Lists (list)
Ordered, changeable collections. You can add, remove, and change items after the list is created. Defined by square brackets [].
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Accesses the first item: "apple"
fruits.append("orange") # Adds an item
fruits[1] = "blueberry" # Changes an item
print(fruits)
Tuples (tuple)
Ordered, unchangeable collections. Once a tuple is created, you can't add, remove, or change items. Defined by parentheses (). They're often used for fixed collections of items, like coordinates.
coordinates = (10.0, 20.0)
print(coordinates[0]) # Accesses the first item: 10.0
# coordinates[1] = 25.0 # This would cause an error!
Dictionaries (dict)
Unordered, changeable collections that store data in key-value pairs. Each item has a unique "key" that you use to look up its "value". Defined by curly braces {}.
person = {
"name": "Bob",
"age": 28,
"city": "New York"
}
print(person["name"]) # Accesses the value associated with key "name": "Bob"
person["age"] = 29 # Changes the value
person["occupation"] = "Engineer" # Adds a new key-value pair
print(person)
Here's how these data structures differ in their characteristics:
graph TD
A["Data Structures"] --> B["Lists (Mutable)"]
A --> C["Tuples (Immutable)"]
A --> D["Dictionaries (Key-Value)"]
B --> B1["Ordered collection"]
B --> B2["Items can be changed/added/removed"]
B --> B3["Syntax: [item1, item2]"]
C --> C1["Ordered collection"]
C --> C2["Items CANNOT be changed/added/removed"]
C --> C3["Syntax: (item1, item2)"]
D --> D1["Unordered collection (in older Python)"]
D --> D2["Stores as key: value pairs"]
D --> D3["Keys must be unique"]
D --> D4["Syntax: {'key1': value1, 'key2': value2}"]
3. Worked Example
Let's imagine you're building a simple system to store information about a student's grades.
student_name = "Charlie"
math_score = 85
science_score = 92
history_score = 78
# Store scores in a list for easy iteration or aggregation
scores = [math_score, science_score, history_score]
# Calculate the average score
total_score = sum(scores)
average_score = total_score / len(scores)
print(f"{student_name}'s scores: {scores}")
print(f"Average score: {average_score:.2f}") # Format to 2 decimal places
# Determine if the student passed overall (e.g., average >= 80)
if average_score >= 80:
print(f"{student_name} passed with distinction!")
elif average_score >= 60:
print(f"{student_name} passed.")
else:
print(f"{student_name} needs to re-study.")
# Use a dictionary to store more detailed student information
student_info = {
"name": student_name,
"age": 16,
"grades": {
"math": math_score,
"science": science_score,
"history": history_score
},
"passed_overall": average_score >= 60 # Boolean based on our logic
}
print(f"\nStudent Info Dictionary: {student_info}")
print(f"Charlie's Math grade: {student_info['grades']['math']}")
4. Key Takeaways
- Variables are named containers for storing different types of data like numbers, text, and booleans.
- Python automatically determines the data type of a variable, but it's good to know what types you're working with.
- Operators (
+,*,==,and) perform computations and comparisons on your data. if/elif/elsestatements let your program make decisions based on conditions.- Lists are ordered, changeable collections, great for sequences of items you might modify.
- Tuples are ordered, unchangeable collections, useful for fixed groups of items.
- Dictionaries store data as key-value pairs, perfect for looking up information by a unique identifier.
Common Mistakes to Avoid:
- Mixing up mutable (lists, dicts) and immutable (tuples) data structures – trying to change a tuple will cause an error.
- Forgetting that list/tuple indexing starts at 0 (the first item is at index 0, not 1).
- Using a single = for comparison instead of == in if statements, which will assign a value instead of checking equality.
- Trying to access a dictionary key that doesn't exist, which will raise a KeyError.
5. Now Try It
Create a Python script that asks you for your favorite color, your age, and whether you own a pet. Store these pieces of information in appropriate variables and then combine them into a single dictionary. Finally, use an if statement to print a different message based on whether you own a pet or not.
What success looks like: Your script takes inputs, stores them, combines them into a dictionary, and then outputs one of two possible sentences depending on your "pet owner" status, all while correctly using the data types.
Frequently asked about Python Fundamentals & Data Structures I
Study this next
Get the full csc curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Create Free Account