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