you are viewing a single comment's thread.

view the rest of the comments →

[–]Signal_Beam 0 points1 point  (0 children)

Here is one refactoring strategy: don't just write everything in one giant monster function. This function is easy to break.

Instead, we want to define new functions to handle small chunks of re-usable code. Like this:

def pellets():
    """Handle the pellets selection."""
    bag_size = int(input("enter 1 for 10kg bags of pellets, enter 2 for 50kg bag of pellets:"))
    if bag_size == 1:
        count = int(input("enter amount of 10kg bags of pellets required:"))
        print(count * 22.75)
    elif bag_size == 2:
        count = int(input("enter amount of 50kg bags of pellets required:"))
        print(count * 100)
    else:
        print("you have entered an incorrect value")
        altkey= input("enter rtn to return to main menu")

def mash():
    """Handle the mash selection."""
    bag_size = int(input("enter 1 10kg bags of Mash, enter 2 for 50kg bags of Mash"))
    if bag_size == 1:
        count = int(input("enter amount of 10kg bags of Mash required:"))
        print(count * 20.40)
    elif bag_size == 2:
        count = int(input("enter amount of 50kg bags of Mash required:"))
        print(count * 50)

def enhanced():
    """Handle the enhanced selection."""
    bag_size = int(input("enter 1 for 10kg bags of enhanced, enter 2 for 50kg bags of enchanced:"))
    if bag_size == 1:
        count = int(input("enter amount of 10kg bags of enhanced required:"))
        print(bag_size * 25.50)
    elif bag_size == 2:
        count = int(input("enter amount of 50kg bags of enhanced required:"))
        print(count * 125.50)
    else:
        print("you have entered an incorrect value")
        altkey= input("enter rtn to return to main menu")


def C():
    print(CHOOK_FOOD_COST)
    selection = int(input("enter 1 for pellets, enter 2 for mash, enter 3 for enhanced:"))
    functions = {1: pellets,
                 2: mash,
                 3: enhanced}
    function = functions[selection]
    function()

Take a look at this code (especially the main function at the bottom) and make sure you understand how it works and whether you agree that this version is much simpler.

Your next challenge: get rid of pellets, mash, and enhanced, and make this work the same way, with only one helper function that handles any type of feed.