100 Days Of Code Challenge – Level Intermediate #1.

Posted in December 19, 2021 by

Categories: Challenges Programming Python

Tags: , , ,

Reading Time: 8 minutes

This is a continuation of the 100 Days of Code Challenge Udemy Course made by Angela Yu. In this series of posts, I write about my participation in this awesome Python course.

If you would like to check the previous post here is a link πŸ‘‡:

In this series of posts, I will be writing about the next days at the level of programming, intermediate.

100 Days of Code Challenge – Day 15.

On this awesome day of coding, Angela was explaining how to install Python on Windows and Mac OSX and how to install PyCharm IDE on those systems.

I already had installed those two ages ago πŸ€“ .

Angela showed me a couple of tips in PyCharm like for example easy renaming function name by choosing to refactor option.

The final coding exercise for day 15 was to program Coffee Machine. There were only input data provided by Angela and the whole program I had to code by myself.

It was very easy for me to complete that project.

You can check the final version under this linkπŸ‘‡ :

The whole code of this app is belowπŸ‘‡ :

  • Main.py
from data import MENU
from data import resources
from art import coffee


def print_report(resource, money):
    """This function takes as an input resources that coffee machine has and money that earned and
    print this data as a report."""
    print("*" * 20)
    print(f"* Water: {resource['water']}ml")
    print(f"* Milk: {resource['milk']}ml")
    print(f"* Coffee: {resource['coffee']}g")
    print(f"* Money: ${money}")


def check_if_there_is_enough_resources(resource, order_ingredients):
    """This function takes as an input resources that coffee machine has and
    ingredients of order and return True if there is no enough resources or
    False is there is enough resources."""
    available_water = resources["water"]
    available_coffee = resources["coffee"]
    available_milk = resources["milk"]

    if item_ingredients["water"] > available_water:
        print("Sorry but there is not enough water. Goodbye!")
        return True
    elif item_ingredients["coffee"] > available_coffee:
        print("Sorry but there is not enough coffee. Goodbye!")
        return True

    if order == "latte" or order == "cappuccino":
        if item_ingredients["milk"] > available_milk:
            print("Sorry but there is no enough milk. Goodbye!")
            return True

    return False


def update_resources(resource, order_ingredients, order):
    """This function takes as an input resources dict and item ingredients and
    return updates resources dict."""

    available_water = resource["water"]
    available_coffee = resource["coffee"]
    available_milk = resource["milk"]

    if order == "latte" or order == "cappuccino":
        order_milk = order_ingredients["milk"]
        available_milk = available_milk - order_milk
        available_milk = 0 if available_milk < 0 else available_milk

    order_coffee = order_ingredients["coffee"]
    available_coffee = available_coffee - order_coffee
    available_coffee = 0 if available_coffee < 0 else available_coffee

    order_water = order_ingredients["water"]
    available_water = available_water - order_water
    available_water = 0 if available_water < 0 else available_water

    resource["water"] = available_water
    resource["milk"] = available_milk
    resource["coffee"] = available_coffee

    return resource


def take_money_from_customer_and_give_change(item_cost):
    """This function takes as an input item cost and takes a coins from customer.
    It calculates how much it is in dollars and it gives change to the customer."""
    print(f"It will be ${item_cost}.")

    quarters = int(input("How many quarters?: "))
    dimes = int(input("How many dimes?: "))
    nickles = int(input("How many nickles?: "))
    pennies = int(input("How many pennies?: "))

    pennies = pennies * 0.01
    nickles = nickles * 0.05
    dimes = dimes * 0.1
    quarters = quarters * 0.25

    total = pennies + nickles + dimes + quarters

    change = total - item_cost

    if change < 0:
        print(f"Not enough money. Money refunded ${total}. Goodbye!")
        return True
    else:
        print("Change is: {:.2f}. Enjoy your coffee.".format(change))

    return False


should_we_continue = False
money = 0
menu_items = ["espresso", "latte", "cappuccino"]

print(coffee)

while not should_we_continue:
    order = input("What would you like? (espresso/latte/cappuccino): ")

    if order.lower() == "report":
        print_report(resources, money)
        continue

    if order.lower() == "off":
        print("Shutting down. Goodbye!")
        break

    if order.lower() not in menu_items:
        print("Sorry but there is no such item in menu. Goodbye!")
        break

    item_ordered = MENU[order]
    item_ingredients = item_ordered["ingredients"]
    item_cost = item_ordered["cost"]

    should_we_continue = check_if_there_is_enough_resources(resources, item_ingredients)
    if should_we_continue:
        break

    should_we_continue = take_money_from_customer_and_give_change(item_cost)
    if not should_we_continue:
        money += item_cost

    resources = update_resources(resources, item_ingredients, order)
  • Data.py
MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}
  • Art.py
coffee = """
     {
      {   }
       }_{ __{
    .-{   }   }-.
   (   }     {   )
   |`-.._____..-'|
   |             ;--.
   |            (__  \/
   |             | )  )
   |             |/  /
   |             /  /  
   |            (  /
   \             y'
    `-.._____..-'
"""

And that is all for day 15th πŸ™‚ .

100 Days of Code Challenge – Day 16.

This day is an introduction to OOP – Object-Oriented Programming.

On this day I was taught about OOP basic principles, what are objects, and classes. What are object attributes and methods.

I was also testing how to create an object with a Turtle library and PrettyTable library and at the same time, I got familiar with PyPi and how to install an external Python library.

The final coding challenge was to use classes created by the instructor and create the same console coffee machine as the day 15th.

This time it is much easier because I have all code already given in classes made by Angela but all I had to do is to use that code and make the program work.

Below is the code of main.py written by me and the code of classes written by the course instructor πŸ‘‡:

  • main.py
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
from time import sleep


def print_menu():
    print("Welcome.")
    print("*" * 30)
    print("Menu:")
    print("1 - Print Report.")
    print("2 - Order Coffee.")
    print("3 - Print Menu again.")
    print("4 - Quit.")


def clear_console():
    print('\n' * 150)


coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()
menu = Menu()

print_menu()
while True:
    choose = int(input("What is your option?: "))
    if choose == 1:
        coffee_maker.report()
        money_machine.report()
    elif choose == 2:
        print("What kind of coffee do you want to order?")
        print(menu.get_items()[:-1])
        coffee_choice = input(": ").lower()
        order = menu.find_drink(coffee_choice)
        if coffee_maker.is_resource_sufficient(order):
            payment_passed = money_machine.make_payment(order.cost)
            if payment_passed:
                coffee_maker.make_coffee(order)
                sleep(4)
                clear_console()
                print_menu()
            else:
                print("Goodbye!")
                break
        else:
            print("Goodbye!")
            break
    elif choose == 3:
        clear_console()
        print_menu()
    elif choose == 4:
        print("Goodbye!")
        break
  • menu.py
class MenuItem:
    """Models each Menu Item."""
    def __init__(self, name, water, milk, coffee, cost):
        self.name = name
        self.cost = cost
        self.ingredients = {
            "water": water,
            "milk": milk,
            "coffee": coffee
        }


class Menu:
    """Models the Menu with drinks."""
    def __init__(self):
        self.menu = [
            MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
            MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
            MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
        ]

    def get_items(self):
        """Returns all the names of the available menu items"""
        options = ""
        for item in self.menu:
            options += f"{item.name}/"
        return options

    def find_drink(self, order_name):
        """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None"""
        for item in self.menu:
            if item.name == order_name:
                return item
        print("Sorry that item is not available.")
  • money_machine.py
class MoneyMachine:

    CURRENCY = "$"

    COIN_VALUES = {
        "quarters": 0.25,
        "dimes": 0.10,
        "nickles": 0.05,
        "pennies": 0.01
    }

    def __init__(self):
        self.profit = 0
        self.money_received = 0

    def report(self):
        """Prints the current profit"""
        print(f"Money: {self.CURRENCY}{self.profit}")

    def process_coins(self):
        """Returns the total calculated from coins inserted."""
        print("Please insert coins.")
        for coin in self.COIN_VALUES:
            self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
        return self.money_received

    def make_payment(self, cost):
        """Returns True when payment is accepted, or False if insufficient."""
        self.process_coins()
        if self.money_received >= cost:
            change = round(self.money_received - cost, 2)
            print(f"Here is {self.CURRENCY}{change} in change.")
            self.profit += cost
            self.money_received = 0
            return True
        else:
            print("Sorry that's not enough money. Money refunded.")
            self.money_received = 0
            return False
  • coffee_maker.py
class CoffeeMaker:
    """Models the machine that makes the coffee"""
    def __init__(self):
        self.resources = {
            "water": 300,
            "milk": 200,
            "coffee": 100,
        }

    def report(self):
        """Prints a report of all resources."""
        print(f"Water: {self.resources['water']}ml")
        print(f"Milk: {self.resources['milk']}ml")
        print(f"Coffee: {self.resources['coffee']}g")

    def is_resource_sufficient(self, drink):
        """Returns True when order can be made, False if ingredients are insufficient."""
        can_make = True
        for item in drink.ingredients:
            if drink.ingredients[item] > self.resources[item]:
                print(f"Sorry there is not enough {item}.")
                can_make = False
        return can_make

    def make_coffee(self, order):
        """Deducts the required ingredients from the resources."""
        for item in order.ingredients:
            self.resources[item] -= order.ingredients[item]
        print(f"Here is your {order.name} β˜•οΈ. Enjoy!")

And that is all for day 16th πŸ™ƒ .

100 Days of Code Challenge – Day 17.

On this day I was learning about how to create a modular OOP small project.

I was creating a few classes and I was writing a code in the main file.

This day was all about OOP and how beneficial it is in programming. I was learning about constructors and initializing an object. Passing to it arguments and such.

The final coding challenge was to build a console Quiz True False App.

Questions are downloaded and implemented from Open Trivia Database.

The easy part was that Angela coded a part of this app but mainly the app was coded by students like me.

Below is the whole code of this app πŸ‘‡:

  • main.py
from data import question_data
from question_model import Question
from quiz_brain import QuizBrain

question_bank = []

for item in question_data:
    question_bank.append(Question(item['question'], item['correct_answer']))

quiz_brain = QuizBrain(question_bank)

while quiz_brain.still_has_questions():
    quiz_brain.next_question()

print("You completed the quiz. Great job!")
print(f"Your final score is {quiz_brain.score}/{quiz_brain.question_number}.")
  • data.py
question_data = [
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "The HTML5 standard was published in 2014.", "correct_answer": "True",
     "incorrect_answers": ["False"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "The common software-programming acronym "I18N" comes from the term "Interlocalization".",
     "correct_answer": "False", "incorrect_answers": ["True"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "FLAC stands for "Free Lossless Audio Condenser"'",
     "correct_answer": "False",
     "incorrect_answers": ["True"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "All program codes have to be compiled into an executable file in order to be run. This file can then be executed on any machine.",
     "correct_answer": "False", "incorrect_answers": ["True"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "MacOS is based on Linux.", "correct_answer": "False", "incorrect_answers": ["True"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "The open source program Redis is a relational database server.",
     "correct_answer": "False",
     "incorrect_answers": ["True"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "AMD created the first consumer 64-bit processor.",
     "correct_answer": "True", "incorrect_answers": ["False"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "Early RAM was directly seated onto the motherboard and could not be easily removed.",
     "correct_answer": "True", "incorrect_answers": ["False"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "Android versions are named in alphabetical order.", "correct_answer": "True",
     "incorrect_answers": ["False"]},
    {"category": "Science: Computers", "type": "boolean", "difficulty": "medium",
     "question": "Linus Sebastian is the creator of the Linux kernel, which went on to be used in Linux, Android, and Chrome OS.",
     "correct_answer": "False", "incorrect_answers": ["True"]}
]
  • question_model.py
class Question:
    def __init__(self, text, answer):
        self.text = text
        self.answer = answer
  • question_brain.py
class QuizBrain:

    def __init__(self, question_list):
        self.question_number = 0
        self.score = 0
        self.question_list = question_list

    def next_question(self):
        current_question = self.question_list[self.question_number]
        question_text = current_question.text
        question_answer = current_question.answer
        self.question_number += 1
        user_answer = input(f"Q.{self.question_number}: {question_text} (True/False): ")
        self.check_answer(user_answer, question_answer)

    def still_has_questions(self):
        return self.question_number < len(self.question_list)

    def check_answer(self, user_answer, correct_answer):
        if user_answer.lower() == correct_answer.lower():
            print("You got it right. Great job!")
            self.score += 1
        else:
            print("You got it wrong. Sorry!")
        print(f"Your current score is: {self.score}/{self.question_number}.")
        print(f"The correct answer is: {correct_answer}.")
        print("\n")

And that is all for day 17th πŸ™‚ .

Conslusions.

I am super happy that I advanced to the intermediate level in this course 😁.

The fact that I started to learn OOP in Python is awesome.

In fact, I already finished one Udemy course dedicated to OOP previously so I got some intermediate skills in this paradigm but I decided I will do this course from top to bottom so some basic stuff may repeat.

In the next article I will write about the next days of intermediate level so stay tuned.

If you like this article and find it valuable you can leave some comments, share it on social media or give a thumb up.

Thank you for your time and have a great day.

Bye πŸ‘‹.


One thought on “100 Days Of Code Challenge – Level Intermediate #1.”

Leave a Reply

Your email address will not be published.

error: Content is protected !!