Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shop Revisted
#1
Buy/add/delete items. May still have a bug or two.

from tabulate import tabulate
from os import system, name
from time import sleep


def clear():
    system('cls' if name == 'nt' else 'clear')

class Product:
    '''
        This class simply holds a dict with item number, item and cost.
        Dict format is number for key and a tuple for holding item and cost
    '''
    def __init__(self):
        self.items = {
            '1': ('hotdog', 1.25),
            '2': ('hamburger', 2.25),
            '3': ('chili cheese fries', 3.25)
        }

    def add(self, item, cost):
        '''
            Method for adding item and cost to items dict.
            Will also edit price if same item is entered
        '''
        for k, v in self.items.items():
            if item in v:
                self.items[k] = (item, cost)
                return
        self.items[f'{len(self.items)+1}'] = (item, cost)

    def delete(self, item):
        '''
            Method for deleting item from items dict
        '''
        key = False
        for k, v in self.items.items():
            if item in v:
                key = k
        if key:
            self.items.pop(key)
            self.items = {str(i+1):value for i, value in enumerate(self.items.values())}
            return True
        return False


class Store:
    '''
        Store class is for displaying number, item, and cost.
    '''
    def display(self, arg):
        items = []
        for k, v in arg.items():
            items.append([k+'.', v[0].title(), f'${v[1]:.2f}'])
        print(tabulate(items, headers=['#','Item','Cost'],tablefmt='fancy_grid'))

    def msg(self, text):
        print('\n'+'*'*round((len(text)/2)-3) + ' Shop ' + '*'*round((len(text)/2)-3))
        print(f'\n{text}\n')


class Controller:
    def __init__(self, product, store):
        '''
            Controller class is for communication between all classes
        '''
        self.product = product
        self.store = store

    def menu(self):
        '''
            Method for getting menu option
        '''
        option = input('\nPlease enter an option.\n>> ')
        if option:
            return option
        return False

    def add(self, item, cost):
        '''
            Method for adding an item
        '''
        controller.product.add(item, cost)
        

    def delete(self, item):
        '''
            Method for deleting an item
        '''
        action = controller.product.delete(item)
        if action:
            return True
        return False

    def get_total(self, amount, price):
        '''
            Method for getting price total
        '''
        return amount*price

if __name__ == '__main__':
    controller = Controller(Product(), Store())
    clear()
    while True:
        print('*'*11 + ' Shop ' + '*'*11)
        controller.store.display(controller.product.items)
        text = 'Options: number = order, admin = add/delete items, q = exit'
        controller.store.msg(text)
        orders = controller.product.items.keys()
        option = controller.menu()

        if option == 'q':
            clear()
            controller.store.msg('Goodbye!')
            break

        if option in orders:
            clear()
            item = controller.product.items[option][0].title()
            text = f'How many boxes of {item}\'s do you want?'
           
            controller.store.msg(text)
            try:
                amount = int(input('>> '))
                price = controller.product.items[option][1]
                total = controller.get_total(amount, price)
                boxes = 'boxes' if amount > 1 else 'box'
            except ValueError:
                clear()
                controller.store.msg('You can only enter whole numbers')
                continue
            clear()
            text = f'You got {amount} {boxes} of {item} for ${total:.2f}'
            controller.store.msg(text)
            sleep(3)
            clear()

        elif option == 'q':
            break

        elif option == 'admin':
            clear()
            text = 'Options: 1 = add, 2 = delete, q = exit'
            controller.store.msg(text)
            while True:
                _ = input('Enter option: ')

                if _ not in ['1', '2', 'q']:
                    clear()
                    text = 'That option does not exist.\nOptions: 1 = add, 2 = delete, q = exit'
                    controller.store.msg(text)
                    continue
                
                if _ == '1':
                    clear()
                    controller.store.display(controller.product.items)
                    text = 'Enter a single item and cost separated by a comma'
                    controller.store.msg(text)
                    item = input('>> ').split(',')

                    if len(item) > 1 and len(item) < 3:
                        try:
                            price = float(item[1])
                        except ValueError:
                            clear()
                            controller.store.msg('Only numbers and floats are allowed.')
                            sleep(3)
                            clear()
                            break

                        controller.add(item[0], float(item[1]))
                        clear()
                        text = f'{item[0].title().strip()} has been added for ${float(item[1].strip()):.2f} a box.'
                        controller.store.msg(text)
                        sleep(3)
                        clear()
                        break
                    else:
                        clear()
                        text = 'That is not the correct format\nEnter a single item and cost separated by a comma.\nOptions: 1 = add, 2 = delete, q = exit\n'
                        controller.store.msg(text)
                        sleep(2)
                        continue
                        
                if _ == '2':
                    controller.store.display(controller.product.items)
                    text = 'Enter the name of an item to be removed.'
                    controller.store.msg(text)
                    item = input('>> ')

                    if item:
                        action = controller.delete(item)
                        if action:
                            clear()
                            text = f'{item.title()} has been removed'
                            controller.store.msg(text)
                            sleep(3)
                            break
                        else:
                            clear()
                            controller.store.display(controller.product.items)
                            text = f'{item.title()} does not exist.\nOptions: 1 = add, 2 = delete, q = exit'
                            controller.store.msg(text)
                    else:
                        clear()
                        controller.store.display(controller.product.items)
                        text = 'Error!\nOptions: 1 = add, 2 = delete, q = exit'
                        controller.store.msg(text)
                        continue

                if _ == 'q':
                    controller.store.msg('Goodbye!')
                    break

        else:
            clear()
            controller.store.msg('Error! That is not a valid option.')
            sleep(3)
            clear()
Gribouillis likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple Text Shop Simulator Feedback Dash 5 3,400 Apr-19-2019, 01:08 PM
Last Post: Dash

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020