{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyOqa52SncyIQAwC+xbU9rG7", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# Ejemplo: Coffee Shop\n", "* Nos piden que digamos qué presupuesto tenemos para la adquisición de un café\n", "* En función del presupuesto nos ofrecen varios tipos de café, de varios precios\n", "* Nos dicen cuánto sobra en cada caso\n", "\n", "https://kinsta.com/es/blog/programacion-orientada-objetos-python" ], "metadata": { "id": "mF_A5wbYFG7z" } }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8RHFiRvj-o5L", "outputId": "b451029d-e31f-4ad0-d666-ede900d25af2" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "What is your budget? 5.75\n", "You can buy the Regular coffee\n", "Here is your change 0.75$\n", "You can buy the Small coffee\n", "Here is your change 3.75$\n" ] } ], "source": [ "class Coffee:\n", " # Constructor\n", " def __init__(self, name, price):\n", " self.name = name\n", " self.price = float(price)\n", " def check_budget(self, budget):\n", " # Check if the budget is valid\n", " if not isinstance(budget, (int, float)):\n", " print('Enter float or int')\n", " exit()\n", " if budget < 0:\n", " print('Sorry you don\\'t have money')\n", " exit()\n", " def get_change(self, budget):\n", " return budget - self.price\n", "\n", " def sell(self, budget):\n", " self.check_budget(budget)\n", " if budget >= self.price:\n", " print(f'You can buy the {self.name} coffee')\n", " if budget == self.price:\n", " print('It\\'s complete')\n", " else:\n", " print(f'Here is your change {self.get_change(budget)}$')\n", "\n", " exit('Thanks for your transaction')\n", "\n", "if __name__ == \"__main__\":\n", " small = Coffee('Small', 2)\n", " regular = Coffee('Regular', 5)\n", " big = Coffee('Big', 6)\n", "\n", " try:\n", " user_budget = float(input('What is your budget? '))\n", " except ValueError:\n", " exit('Please enter a number')\n", "\n", " for coffee in [big, regular, small]:\n", " coffee.sell(user_budget)\n", "\n", " #e = Coffee(\"espresso\", 5.40)\n", " #e.sell(100)" ] } ] }