-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrow_percentage.py
More file actions
36 lines (28 loc) · 1.02 KB
/
Copy pathgrow_percentage.py
File metadata and controls
36 lines (28 loc) · 1.02 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
"""Interactively calculate percentage changes between consecutive numbers.
Usage: python3.14 grow_percentage.py
Enter one number per prompt; press Ctrl+D or Ctrl+C to exit.
"""
from __future__ import annotations
def percent_delta(basis: float, new: float) -> float:
"""Return the percentage change from *basis* to *new*."""
if basis == 0:
raise ValueError("the previous value must not be zero")
return ((100 * new) / basis) - 100
def main() -> int:
previous: float | None = None
while True:
try:
value = float(input(">> "))
if previous is not None:
try:
print(f"{percent_delta(previous, value):.2f}%")
except ValueError as exc:
print(f"Invalid data: {exc}")
previous = value
except ValueError:
print("Invalid data: enter a number")
except (EOFError, KeyboardInterrupt):
print()
return 0
if __name__ == "__main__":
raise SystemExit(main())