$ cat fuel.py
def main():
fraction_str = input("Enter fraction, formatted as X/Y, of how much fuel is in the tank: ")
percentage=convert(fraction_str)
print(gauge(percentage))
def convert(fraction):
(x,y) = fraction.split("/")
x_int=int(x)
y_int=int(y)
if x_int > y_int:
raise ValueError
if y_int == 0:
raise ZeroDivisionError
percentage=round(x_int/y_int*100)
return percentage
def gauge(percentage):
if percentage <= 1:
return "E"
elif percentage >= 99:
return "F"
else:
return f'{percentage}%'
if __name__ == "__main__":
main()
$
The test program:
$ cat test_fuel.py
import pytest
from fuel import convert
from fuel import gauge
def test_convert():
assert convert("1/100") == 1
assert convert("2/10") == 20
assert convert("0/10") == 0
with pytest.raises(ValueError):
convert("banana/apple")
def test_gauge():
assert gauge(1) == "E"
assert gauge(100) == "F"
assert gauge(22) == "22%"
!$ cat fuel.py !def main(): ! fraction_str = input("Enter fraction, formatted as X/Y, of how much fuel is in the tank: ") ! percentage=convert(fraction_str) ! print(gauge(percentage)) ! !def convert(fraction): ! (x,y) = fraction.split("/") ! x_int=int(x) ! y_int=int(y) ! if x_int > y_int: ! raise ValueError ! if y_int == 0: ! raise ZeroDivisionError ! percentage=round(x_int/y_int*100) ! return percentage ! !def gauge(percentage): ! if percentage <= 1: ! return "E" ! elif percentage >= 99: ! return "F" ! else: ! return f'{percentage}%' ! !if __name__ == "__main__": ! main() !$ !
The test program:!$ cat test_fuel.py !import pytest !from fuel import convert !from fuel import gauge ! !def test_convert(): ! assert convert("1/100") == 1 ! assert convert("2/10") == 20 ! assert convert("0/10") == 0 ! with pytest.raises(ValueError): ! convert("banana/apple") ! ! !def test_gauge(): ! assert gauge(1) == "E" ! assert gauge(100) == "F" ! assert gauge(22) == "22%" !