Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Choices matter

I'm trying to make a simple menu where if you press one you get one option and if you press two you get a different one within if statements. Basically, an online order form if you were ordering girl scout cookies through an app and at the bottom it'll tell you how much you're buying and how much it'll all cost. I think I got the format down, but I can't get the variables to show up. Every time I hit '1' I get nothing when it's supposed to print something or move on to the next step.
Python:
#Define Variables
cont = input("Would you like to start?> (y/n)")
item_cnt = 0
order_total = 0
choice_1 = "Savannah"
choice_2 = "Thin Mints"
choice_3 = "Tagalongs"

# Input and process
print("Welcome!")

while cont.lower() == "y":
    while True:
        name = input("Who is this order for?>")

        if len(name) < 1 or len(name) > 20:
            print("name error: name must be between 1 and 20 characters.")
        else:
            break

    print("Please choose your order based on the number.")
    choice_1 = print("1. Savannah $3.50 per box.")
    choice_2 = print("2. Thin Mints $3.50 per box.")
    choice_3 = print("3. Tagalongs $5.00 per box.")

    while True:
        choice_1 = int(1)

while choice_1 () == "1":
    while True:
        choice_1 = int(1)

        if 1:
            print("You have chosen Savannah for $3.50 per box.")
        else:
            break

    while True:
        if 2:
            print("You have chosen Thin Mints $3.50 per box.")
        else:
            break

        while True:
            if 3:
                print("You have chosen Tagalongs $5.00 per box.")
            else:
                break
 
Here is an example using a dict combined with a tuple. I only did limited error checking. Using only one while loop.
I will leave getting totals to you.

Python:
'''
define product dict. Key will be a string number,
value will be a tuple with item and price
'''
product = {
    '1': ('savannah',3.50),
    '2': ('thin mints', 3.50),
    '3': ('tagalongs', 5.00)
}


# Start the while loop
while True:
    # List our products and price
    print('Items:')
    for k, v in product.items():
        print(f'{k}. {v[0].title()} ${v[1]:.2f} each box.')

    # Get user input of a number / If user wants to exit give the option and break
    item = input('\nPlease enter an item number or q to exit.\n>> ')
    if item == 'q':
        break

    # Check if product is in our product dict. Ask if to continue or exit
    if item not in product.keys():
        print('\nThat item does not exist.\nWould you like to try again? y/n')
        yesno = input('>> ')
        if yesno.lower() == 'n':
            print('Goodbye!')
            break

    # Product was in our dict display message. Ask to continue or quit  
    else:
        print(f'You chose {product[item][0].title()} for ${product[item][1]:.2f} a box.')
        yesno = input('\npress enter to continue or q to exit.')
        if yesno == 'q':
            break
 
Ow... 3 levels of loop nesting, that hurts the brain. The logic behind it is impossible to see, at least for me. Also, the indentation looks off. In which case, this being Python, anything could happen.
You really need to think about your program logic and ask yourself how many loops are necessary here.
 
I see only two input() functions. None of them asking for a 1 or 2 as it's input.
One seems to be asking for y or n, and the other for a name.
 
Here is an example using a dict combined with a tuple. I only did limited error checking. Using only one while loop.
I will leave getting totals to you.

Python:
'''
define product dict. Key will be a string number,
value will be a tuple with item and price
'''
product = {
    '1': ('savannah',3.50),
    '2': ('thin mints', 3.50),
    '3': ('tagalongs', 5.00)
}


# Start the while loop
while True:
    # List our products and price
    print('Items:')
    for k, v in product.items():
        print(f'{k}. {v[0].title()} ${v[1]:.2f} each box.')

    # Get user input of a number / If user wants to exit give the option and break
    item = input('\nPlease enter an item number or q to exit.\n>> ')
    if item == 'q':
        break

    # Check if product is in our product dict. Ask if to continue or exit
    if item not in product.keys():
        print('\nThat item does not exist.\nWould you like to try again? y/n')
        yesno = input('>> ')
        if yesno.lower() == 'n':
            print('Goodbye!')
            break

    # Product was in our dict display message. Ask to continue or quit 
    else:
        print(f'You chose {product[item][0].title()} for ${product[item][1]:.2f} a box.')
        yesno = input('\npress enter to continue or q to exit.')
        if yesno == 'q':
            break
Thank you again so much for your help!
 
Ow... 3 levels of loop nesting, that hurts the brain. The logic behind it is impossible to see, at least for me. Also, the indentation looks off. In which case, this being Python, anything could happen.
You really need to think about your program logic and ask yourself how many loops are necessary here.
Thank you, it's my first attempt at python so I appreciate any input.
 
I took it a step further. Probably some bugs. Started getting tired.
Will require install tabulate

Python:
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()
 
Last edited:

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom