Modularity, Reusability, and Anonymous Functions

Modularity and Reusability

Building on what we have learned so far, consider a comprehensive program that allows us to shop for fruits and vegetables. Here we have 3 Python files named “main.py”, “fruits.py”, and “vegetables.py” and all of these are stored in a separate folder called “Shopping_Module”.
Here the main.py will have code that works with functions stored in fruits.py and vegetables.py, and will run the code in a loop until the user decides to quit the program. Let’s see what the result would be:

Here the program asks if they want to buy fruits or vegetables or exit from the program, and since this is in a loop, this will go on till the user decides to quit. Here the program asks the user for the name as well as the count of the fruit/vegetable they want. The program then checks if that fruit/vegetable is there and also checks if they can give the user the required number of fruits or vegetables.

When a user enters a fruit or vegetable that is not there or if the required count is greater than what is available the program tells us accordingly.

 

When the user desires to exit the program, the program works as shown:

Consider the entire code for the above program:

import fruits, vegetables


def buy_fruits():
    fruit_name = input("Enter Fruit: ")  # taking fruit name
    fruit_count = int(input("Enter Required Count: "))  # taking fruit count
    fruits.calculate_fruit_availability(fruit_name, fruit_count)


def buy_vegetables():
    vegetable_name = input("Enter vegetable: ")  # taking vegetable name
    vegetable_count = int(input("Enter required count: "))  # taking vegetable count
    vegetables.calculate_vegetable_availability(vegetable_name, vegetable_count)


continue_shopping = True

print("\nWelcome to the fruits and vegetables store")

while continue_shopping:

    print("\nWould you like to:")
    print("1. Buy fruits")
    print("2. Buy vegetables")
    print("3. Exit")

    user_input = int(input("\nEnter 1 or 2 or 3 as per your choice:"))
    print("")

    if user_input == 1:
        buy_fruits()

    elif user_input == 2:
        buy_vegetables()

    elif user_input == 3:
        print("Goodbye!")
        continue_shopping = False

    else:
        print("Entered wrong input")

Code from main.py

fruits = {
    # "Fruit name": "No. of fruits available"
    "Apples": 200,
    "Bananas": 193,
    "Oranges": 189,
    "Pineapples": 197,
    "Watermelons": 151
}


def calculate_fruit_availability(fruit_name, required_count):
    # if requested fruit is there in the list of keys from the fruits dictionary
    if fruit_name in fruits.keys():

        print("Requested fruit is:", fruit_name)

        # for a dict, we pass the required key as an index to get the required item
        stock_count = fruits[fruit_name]

        # if the user needs more than the available fruits
        if required_count > stock_count:
            print("We don't have that many", fruit_name.lower())

        # if the user needs less than or equal to the available fruits
        else:
            print("Yes", required_count, fruit_name.lower(), "are available")

    # if requested fruit is not available
    else:
        print("Requested fruit is not available")

 

Code from fruits.py

vegetables = {
    # "Vegetable name": "No. of Vegetable available"
    "Carrots": 191,
    "Beans": 179,
    "Potatoes": 150,
    "Cabbage": 171,
    "Radish": 200
}


def calculate_vegetable_availability(vegetables_name, required_count):
    # if requested vegetable is there in the list of keys from the vegetables dictionary
    if vegetables_name in vegetables.keys():

        print("Requested vegetable is:", vegetables_name)

        # for a dict, we pass the required key as an index to get the required item
        stock_count = vegetables[vegetables_name]

        # if the user needs more than the available vegetables
        if required_count > stock_count:
            print("We don't have that many", vegetables_name.lower())

        # if the user needs less than or equal to the available vegetables
        else:
            print("Yes", required_count, vegetables_name.lower(), "are available")

    # if requested vegetable is not available
    else:

Code from vegetables.py

Here we see the concepts of Modularity and Reusability which aid in a putting together that is neatly packed.
Modularity is the concept by which we split our program into multiple files so that it is more readable. It is possible to put the above program into one single Python file, but just imagine how cluttered and messy it would be. All of the components of each file are separated based on the purpose it serves, we could have combined the contents of fruits.py with the contents of vegetables.py into one file but would look cluttered and has the potential to confuse people who read our code. Reusability as the name suggests is calling a block of code without having to write it all again, specifically we achieve this through the use of functions.
Feel free to modify the above code as you wish, and try to make the program even more complex.

Anonymous Functions

Functions that are defined without a name and by using Lambda expressions are referred to as Anonymous Functions. However anonymous functions can take any number of arguments and returns only on expression. They also cannot return statements.
Take a look at the example:

value1 = lambda x: x * 50
value2 = lambda x: x * 50 / 5
value3 = lambda x, y: x * 30 - y

print(value1(3))
print(value2(3))
print(value3(3, 5))

This gives the output as:

Anonymous Functions are best used within another function, i.e., when we want a function to do a small execution, like the following:

def anonymous_function_example(multiplier):
  return lambda number: number * multiplier

times_five = anonymous_function_example(5)
times_ten = anonymous_function_example(10)

print("3 * 5 =", times_five(3))
print("3 * 10 =", times_ten(3))

What have we learned?

•What is Modularity in Python?
•What is Reusability in Python?
•What are Anonymous Functions?
•How do we create an Anonymous Function?
•Which keyword is used to create an Anonymous Function?
•When is the best scenario to use an •Anonymous Function?

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments