|
| 1 | +"""A program to calculate tea price by cup size""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import sys |
| 7 | + |
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
| 10 | +# Error message constants |
| 11 | +ERROR_MESSAGES = { |
| 12 | + "no_input": "No input provided", |
| 13 | + "interrupted": "User interrupted input", |
| 14 | + "no_data": "No input received", |
| 15 | + "invalid_choice": "Invalid snack choice", |
| 16 | +} |
| 17 | + |
| 18 | +PRICE_CHART = { |
| 19 | + "small": 10, |
| 20 | + "medium": 15, |
| 21 | + "large": 20, |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +class CupSizeSelectorError(Exception): |
| 26 | + """Base exception for cup size selector errors.""" |
| 27 | + |
| 28 | + |
| 29 | +class InvalidInputError(CupSizeSelectorError): |
| 30 | + """Raised when the user provides invalid input.""" |
| 31 | + |
| 32 | + |
| 33 | +def get_user_input() -> str: |
| 34 | + """Get user input from the console.""" |
| 35 | + try: |
| 36 | + user_input = input("\nPlease provide your choice of cup size: ") |
| 37 | + cleaned_input = user_input.strip().lower() |
| 38 | + |
| 39 | + if not cleaned_input: |
| 40 | + raise InvalidInputError(ERROR_MESSAGES["no_input"]) |
| 41 | + return cleaned_input # noqa: TRY300 |
| 42 | + except KeyboardInterrupt as e: |
| 43 | + raise InvalidInputError(ERROR_MESSAGES["interrupted"]) from e |
| 44 | + except EOFError as e: |
| 45 | + raise InvalidInputError(ERROR_MESSAGES["no_data"]) from e |
| 46 | + |
| 47 | + |
| 48 | +def process_user_request(user_input: str) -> None: |
| 49 | + """Process the user request and ask for the appropriate price""" |
| 50 | + if user_input in PRICE_CHART: |
| 51 | + logger.info("Price of %s cup of team would be %d", user_input, PRICE_CHART[user_input]) |
| 52 | + else: |
| 53 | + logger.info("Sorry, unknown cup size. Please try again later.") |
| 54 | + |
| 55 | + |
| 56 | +def main() -> None: |
| 57 | + """Main function to run the snack selector.""" |
| 58 | + logging.basicConfig( |
| 59 | + level=logging.INFO, |
| 60 | + format="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s:%(lineno)d - %(message)s", |
| 61 | + datefmt="%Y-%m-%d %H:%M:%S", |
| 62 | + ) |
| 63 | + try: |
| 64 | + user_input = get_user_input() |
| 65 | + process_user_request(user_input) |
| 66 | + except InvalidInputError: |
| 67 | + logger.exception("Invalid input") |
| 68 | + sys.exit(1) |
| 69 | + except Exception: |
| 70 | + logger.exception("Unexpected error") |
| 71 | + sys.exit(1) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + main() |
0 commit comments