Skip to content

Commit 1a48037

Browse files
Fix formatting for negative balances and ensure totals display correctly
1 parent 3073be4 commit 1a48037

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

sprint-5/prep-exercises/type-checking.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,29 +49,43 @@
4949
#Here is the corrected code with type annotations and fixed function calls:
5050

5151
from typing import Dict
52+
5253
def open_account(balances: Dict[str, int], name: str, amount: int) -> None:
5354
balances[name] = amount
55+
5456
def sum_balances(accounts: Dict[str, int]) -> int:
5557
total = 0
5658
for name, pence in accounts.items():
5759
print(f"{name} had balance {pence}")
5860
total += pence
5961
return total
62+
6063
def format_pence_as_string(total_pence: int) -> str:
64+
negative = total_pence < 0
65+
total_pence = abs(total_pence)
66+
6167
if total_pence < 100:
62-
return f"{total_pence}p"
63-
pounds = int(total_pence / 100)
64-
pence = total_pence % 100
65-
return f"£{pounds}.{pence:02d}"
68+
result = f"{total_pence}p"
69+
else:
70+
pounds = total_pence // 100
71+
pence = total_pence % 100
72+
result = f"£{pounds}.{pence:02d}"
73+
74+
return f"-{result}" if negative else result
75+
6676
balances: Dict[str, int] = {
6777
"Sima": 700,
6878
"Linn": 545,
6979
"Georg": 831,
7080
}
81+
7182
open_account(balances, "Tobi", 913)
72-
open_account(balances, "Olya", 713)
83+
open_account(balances, "Olya", 713)
84+
open_account(balances, "Alex", -250)
85+
7386
total_pence = sum_balances(balances)
7487
total_string = format_pence_as_string(total_pence)
88+
7589
print(f"The bank accounts total {total_string}")
7690

7791
# Now, when I run mypy on the corrected code, I get no type errors, indicating that all type annotations are correct and the bugs have been fixed.with the result:"# Success: no issues found in 1 source file"

0 commit comments

Comments
 (0)