Код: Выделить всё
import sys
class Jar:
def __init__(self, current=0, capacity=12):
if capacity < 1:
raise ValueError("cannot be negative cookies")
self._capacity = capacity
if current < 0 or current > self.capacity:
raise ValueError("Invalid initial number of cookies")
self.current = current
def __str__(self):
return "🍪" * self.current
def deposit(self, n):
jar_total = self.current + n
if jar_total > self.capacity:
raise ValueError ("too many cookies")
self.current = jar_total
def withdraw(self, n):
jar_total = self.current - n
if jar_total < 0:
raise ValueError ("not enough cookies")
self.current = jar_total
@property
def capacity(self):
return self._capacity
@property
def size(self):
return self.current
def main():
my_jar = Jar()
while True:
user_action = input("deposit of withdraw? (or exit to quit:) ").strip().lower()
if user_action == "exit":
print("Goodbye")
break
if user_action in ["deposit", "withdraw"]:
try:
n = int(input("how many cookies?: "))
if user_action == "deposit":
my_jar.deposit(n)
else:
my_jar.withdraw(n)
print(f"current number of cookies in the jar: {my_jar.size}")
print(my_jar)
except ValueError as e:
print(f"error:{e}")
else:
print("options are: deposit, withdraw or exit ya dam fool!")
if __name__ == "__main__":
main()
Код: Выделить всё
from jar import Jar
def test_init():
jar = Jar()
assert jar.current == 0
assert jar.capacity == 12
jar = Jar(5, 10)
assert jar.current == 5
assert jar.capacity == 10
def test_str():
jar = Jar()
assert str(jar) == ""
jar.deposit(1)
assert str(jar) == "🍪"
jar.deposit(11)
assert str(jar) == "🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪"
def test_deposit():
jar = Jar()
assert str(jar) == ""
jar.deposit(1)
assert str(jar) == "🍪"
jar.deposit(5)
assert str(jar) == "🍪🍪🍪🍪🍪🍪"
jar = Jar(0, 6)
jar.deposit(6)
assert jar.size == 6
def test_withdraw():
jar = Jar(12)
assert str(jar) == "🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪"
jar.withdraw(5)
assert str(jar) == "🍪🍪🍪🍪🍪🍪🍪"
jar.withdraw(7)
assert str(jar) == ""
Подробнее здесь: https://stackoverflow.com/questions/787 ... cookie-jar