Skip to content

Commit da24534

Browse files
committed
previous changes splitting expense calculator
1 parent bee1350 commit da24534

12 files changed

Lines changed: 295 additions & 389 deletions

‎.DS_Store‎

4 KB
Binary file not shown.

‎course_files/scripts/basics.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
def get_category_total(expenses, category):
2+
"""Simple math logic to filter and sum expenses."""
3+
return sum(amount for cat, amount in expenses if cat == category)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def load_expenses(filename):
2+
"""Uses try-except and a for loop to load data."""
3+
data = []
4+
try:
5+
with open(filename, "r") as file:
6+
for line in file:
7+
parts = line.strip().split(",")
8+
if len(parts) == 2:
9+
data.append([parts[0].lower(), float(parts[1])])
10+
except FileNotFoundError:
11+
print("No existing records found. Starting fresh.")
12+
return data
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def save_expenses(filename, expenses):
2+
"""Uses the 'with' keyword to safely write to a file."""
3+
with open(filename, "w") as file:
4+
for cat, amount in expenses:
5+
file.write(f"{cat},{amount}\n")
6+
print("All expenses saved successfully.")
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def collect_expenses(thresholds, expenses, get_total_func, check_logic_func):
2+
"""Uses a while loop to interact with the user."""
3+
print("Enter your expenses. Type 'done' to finish.\n")
4+
5+
while True:
6+
category = input("Category (food, transport, entertainment, other): ").lower()
7+
if category == "done":
8+
break
9+
10+
amount_str = input("Amount: ")
11+
12+
# Validation
13+
if category in thresholds and amount_str.replace('.', '', 1).isdigit():
14+
amount = float(amount_str)
15+
expenses.append([category, amount])
16+
17+
# Use the passed-in logic functions
18+
current_total = get_total_func(expenses, category)
19+
check_logic_func(category, current_total, thresholds)
20+
else:
21+
print("Invalid input. Try again.\n")

‎course_files/scripts/logic.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def check_threshold(category, current_total, thresholds):
2+
"""Handles the conditional logic for budget warnings."""
3+
limit = thresholds.get(category, 0)
4+
if current_total > limit:
5+
print(f"Warning: You have exceeded the {category} threshold!")
6+
print(f"Total spent in {category}: {current_total}")
7+
else:
8+
remaining = limit - current_total
9+
print(f"Added to {category}.")
10+
print(f"Total spent in {category}: {current_total}")
11+
print(f"Amount left for {category}: {remaining}\n")

‎course_files/scripts/main.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import file_reader
2+
import file_writer
3+
import basics
4+
import logic
5+
import input_handler
6+
import summary
7+
8+
# 1. Variable Assignments
9+
FILE_NAME = "expenses.csv"
10+
THRESHOLDS = {
11+
"food": 100.0,
12+
"transport": 50.0,
13+
"entertainment": 80.0,
14+
"other": 70.0
15+
}
16+
17+
# 2. Function Calls
18+
# Load data from the CSV (Uses Try/Except)
19+
current_expenses = file_reader.load_expenses(FILE_NAME)
20+
21+
# Run the input loop (Uses While Loop)
22+
input_handler.collect_expenses(
23+
THRESHOLDS,
24+
current_expenses,
25+
basics.get_category_total,
26+
logic.check_threshold
27+
)
28+
29+
# Display the final list (Uses For Loop)
30+
summary.display_summary(current_expenses)
31+
32+
# Save data back to the file (Uses 'With' statement)
33+
file_writer.save_expenses(FILE_NAME, current_expenses)

‎course_files/scripts/summary.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def display_summary(expenses):
2+
"""Uses a for loop to iterate through the data and print a report."""
3+
print("\n--- Expense Summary ---")
4+
for item in expenses:
5+
category = item[0]
6+
amount = item[1]
7+
print(f"Category: {category.capitalize()} | Amount: ${amount:.2f}")
8+
print("-----------------------\n")
Lines changed: 166 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ title: Data Types and Operators
55
::: {.callout-tip}
66
#### Learning Objectives
77

8-
- Learn about python data types and operators
8+
- Learn about python data types
99
- Learn when to use different data types
1010

1111
:::
1212

13-
## Python Data types
13+
## Introducing python Data types
1414

1515
In programming, **data types** define the kind of data a variable can hold, such as numbers, text, or more complex structures, and they determine what operations can be performed on that data.
1616

@@ -21,44 +21,87 @@ Using data types in Python is straightforward: you assign a value to a variable,
2121
For example, `x = 10` creates an integer, whereas `x = 10.3` creates a float.
2222
A float in a decimal placed number and is stored in python in a 64 bit format.
2323

24-
For an overview of data types use the cheat sheet.
24+
For an overview of data types use the **cheat sheet**.
2525

26-
### Primitive Data Types
26+
::: {.callout-note}
2727

28-
Primitive data types contain single values e.g. numbers and words
28+
To check the data type of a python object use the ```type()``` function.
2929

30-
The main thing to remember is that sequences of letters like words are called strings and require quotation marks around them:
30+
```{python}
31+
32+
x = 10
33+
print(type(x))
34+
35+
```
36+
:::
37+
38+
39+
## Primitive Data Types
40+
41+
Primitive data types contain single values e.g. numbers and words.
42+
43+
### Numerical data types
44+
45+
Python has three numerical data types:
46+
- integers: whole numbers `int`
47+
- floats: decimal placed numbers which are also known as floating point numbers `float`
48+
- complex numbers: python has direct support for complex numbers (*a + bi*). These are not used often by most python users and will not be discussed further in this course.
49+
50+
### Words and text
51+
52+
Sequences of letters like words are called strings and require quotation marks around them:
3153

3254
```name = "Alice"``` creates a string.
3355

56+
Strings can be single words or paragraphs.
57+
58+
### Boolean: true or false
59+
3460
The boolean data types use the key words ```True``` and ```False```
3561

62+
### The placeholder
63+
3664
```None``` can also be used as a placeholder for a variable has no meaningful value yet.
3765

38-
Understanding data types is essential for writing correct programs, performing calculations, and managing data efficiently.
39-
Data types behave slightly differently in different languages for example the way numbers a rounded.
66+
## The importance of data types
4067

41-
## Python operators
68+
Python makes working with data types easier than many other programming languages. When you create a variable, Python automatically decides what type of data it is based on the value you give it. In most cases, the correct data type is a straightforward choice. For example, when indexing a table or referring to whole number counts integers are used, whereas measurements often require decimal places and so floats are used.
4269

43-
**operators** are symbols or keywords used to perform operations on data and variables, like calculations or comparisons.
44-
This of mathematical singles like ```+``` 0r ```<```.
70+
That said, Python’s data types each have their own rules and behaviors. As you’ll see in the following exercises, understanding these differences is important for writing correct programs, doing calculations, and working with data effectively. It’s also helpful to know that data types can behave differently in other languages—for example, in how numbers are rounded.
4571

46-
Most of the operators in python make sense. Use the cheat sheet table to look them up if you need.
72+
## Immutable versus mutable data types
4773

48-
::: {.callout-exercise}
49-
#### Using operators
74+
In Python, data types can be either **mutable** or **immutable**, which refers to whether their values can be changed after they are created.
75+
76+
Most python primitive data types, such as integers, floats, booleans, and strings, are **immutable**, meaning their values cannot be changed after they are created. If you appear to modify one of these values, Python actually creates a new object instead with the same variable name. This makes primitive types simple and predictable to work with, especially for beginners.
77+
78+
In contrast, composite data types (like lists, tuples, sets, and dictionaries) can be either **mutable** or **immutable**. Two types that are **mutable**, and so can be changed after they are created are lists and dictionaries. We will look at composite data types in more detail in the next section.
79+
80+
::: {.callout-note}
5081

51-
Use the console to test different operators from the tables.
52-
Try adjusting the operators in the expenses_calculator.py script and seeing how the behaviour of the script changes.
82+
To demonstrate that the primitive data types are immutable you ca change their value and use the id() function to check where they are located in memory.
5383

84+
```{python}
85+
86+
x = 10
87+
print("Initial value:", x)
88+
print("Initial memory location:", id(x))
89+
90+
# "Modify" the integer
91+
x = 15
92+
93+
print("New value:", x)
94+
print("New memory location:", id(x))
95+
96+
```
5497
:::
5598

5699

57100
## Composite Data Types - The exciting stuff!
58101

59-
Complex data types is where things really become interesting and the basis for more complex programming
102+
Composite data types are where things start to become more interesting and form the foundation for more complex programming.
60103

61-
In Python, composite data types allow you to store multiple values in a single variable. They can hold a collection of items, which can be of different data types. The main composite data types in Python are:
104+
In Python, composite data types allow you to store multiple values within a single variable. These values are grouped together as a collection, and they can even be of different data types. The main composite data types in Python are:
62105

63106
**Lists**
64107

@@ -88,7 +131,7 @@ In Python, composite data types allow you to store multiple values in a single v
88131

89132
Let's initialize one of each composite data type with a list of 10 animals, and then demonstrate some of the main differences.
90133

91-
```
134+
```python
92135
# Initialize a list of animals
93136
animal_list = ["Dog", "Cat", "Elephant", "Lion", "Tiger", "Giraffe", "Zebra", "Monkey", "Snake", "Rabbit"]
94137

@@ -213,11 +256,114 @@ Get the number of elements in the list.
213256

214257
`length = len(my_list) # 8`
215258

216-
**Numeric operators e.g. Append multiple repeats**
259+
**Numeric operations e.g. Append multiple repeats**
217260

218261
`my_list * 2 # [20, 8, 7, 6, 5, 4, 3, 1, 20, 8, 7, 6, 5, 4, 3, 1]`
219262

220263

264+
## Converting between data types
265+
266+
All built-in data types in Python have associated built-in functions that allow you to convert values from one data type to another or explicitly create an object of that type. Examples of converting between data types are presented below.
267+
268+
It is not possible to convert between all data types; some conversions require additional information and input.
269+
270+
Resources about data types can be found in the python documentation:
271+
https://docs.python.org/3/library/functions.html
272+
https://docs.python.org/3/library/stdtypes.html
273+
274+
Examples of converting between data types:
275+
276+
277+
278+
**1. Converting int to float**
279+
```
280+
x = 5 # integer
281+
y = float(x) # converting to float
282+
print(y)
283+
```
284+
Output:
285+
```
286+
5.0
287+
```
288+
289+
**2. Converting float to int**
290+
```
291+
x = 3.23 # float
292+
y = int(x) # converting to int
293+
print(b)
294+
```
295+
Output:
296+
```
297+
3
298+
```
299+
300+
**3. Converting int to str**
301+
```
302+
x = 10 # integer
303+
y = str(x) # converting to string
304+
print(y)
305+
```
306+
Output:
307+
```
308+
'10'
309+
```
310+
311+
**4. Converting str to int**
312+
```
313+
x = "123" # string
314+
y = int(x) # converting to int
315+
print(y)
316+
```
317+
Output:
318+
```
319+
123
320+
```
321+
322+
**5. Converting str to float**
323+
```
324+
x = "45.67" # string
325+
y = float(x) # converting to float
326+
print(x)
327+
```
328+
Output:
329+
```
330+
45.67
331+
```
332+
333+
**6. Converting list to tuple**
334+
```
335+
my_list = [1, 2, 3] # list
336+
my_tuple = tuple(my_list) # converting to tuple
337+
print(my_tuple)
338+
```
339+
Output:
340+
```
341+
(1, 2, 3)
342+
```
343+
344+
**7. Converting tuple to list**
345+
```
346+
my_tuple2 = (4, 5, 6) # tuple
347+
my_list2 = list(my_tuple2) # converting to list
348+
print(my_list2)
349+
```
350+
Output:
351+
```
352+
[4, 5, 6]
353+
```
354+
355+
**8. Converting int to bool**
356+
```
357+
num_bool = 0 # integer
358+
bool_value = bool(num_bool) # converting to boolean
359+
print(bool_value)
360+
```
361+
Output:
362+
```
363+
False
364+
```
365+
366+
221367
## Exercises
222368

223369

‎materials/03_python_operators.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
title: Data Types and Operators
3+
---
4+
5+
::: {.callout-tip}
6+
#### Learning Objectives
7+
8+
- Learn about python data types and operators
9+
- Learn when to use different data types
10+
11+
:::
12+
13+
14+
15+
## Python operators
16+
17+
**operators** are symbols or keywords used to perform operations on data and variables, like calculations or comparisons.
18+
This of mathematical singles like ```+``` 0r ```<```.
19+
20+
Most of the operators in python make sense. Use the cheat sheet table to look them up if you need.
21+
22+
::: {.callout-exercise}
23+
#### Using operators
24+
25+
Use the console to test different operators from the tables.
26+
Try adjusting the operators in the expenses_calculator.py script and seeing how the behaviour of the script changes.
27+
28+
:::
29+
30+
::: {.callout-warning}
31+
Strings in Python are immutable, meaning they cannot be changed after they are created. When a string is modified—such as through concatenation or other operations—Python creates a new string object instead of altering the original one. Because of this, repeatedly building strings using operations like + in loops can be inefficient in both time and memory, since many intermediate string objects may be created. Python automatically manages memory using a process called garbage collection, which is how it reclaims memory from objects that are no longer needed. More specifically, garbage collection removes objects that are no longer reachable in the program—meaning there are no variable names or references pointing to them anymore, either because they were reassigned or deleted. In most cases, you do not need to manage this process manually. Instead, for efficiently building large strings, it is better to use tools designed for this purpose, such as ''.join() or io.StringIO, which reduce the number of temporary string objects created.
32+
```
33+

0 commit comments

Comments
 (0)