Skip to content

Commit 732a40b

Browse files
committed
Type checking with mypy
1 parent cc96971 commit 732a40b

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#==============================================================================
2+
# Do not run the following code.
3+
4+
# This code contains bugs related to types. They are bugs mypy can catch.
5+
6+
# Read this code to understand what it’s trying to do. Add type annotations to the method parameters and return types of this code.
7+
# Run the code through mypy, and fix all of the bugs that show up.
8+
# When you’re confident all of the type annotations are correct, and the bugs are fixed, run the code and check it works.
9+
#==============================================================================
10+
11+
def open_account(balances: dict[str, int], name: str, amount: int) -> None:
12+
balances[name] = amount
13+
14+
def sum_balances(accounts: dict[str, int]) -> int:
15+
total = 0
16+
for name, pence in accounts.items():
17+
print(f"{name} had balance {pence}")
18+
total += pence
19+
return total
20+
21+
def format_pence_as_string(total_pence: int) -> str:
22+
if total_pence < 100:
23+
return f"{total_pence}p"
24+
pounds = int(total_pence / 100)
25+
pence = total_pence % 100
26+
return f"£{pounds}.{pence:02d}"
27+
28+
balances: dict[str, int] = {
29+
"Sima": 700,
30+
"Linn": 545,
31+
"Georg": 831,
32+
}
33+
34+
open_account(balances, "Tobi", 913)
35+
open_account(balances, "Olya", 713)
36+
37+
total_pence = sum_balances(balances)
38+
total_string = format_pence_as_string(total_pence)
39+
40+
print(f"The bank accounts total {total_string}")

0 commit comments

Comments
 (0)