Blog Post #33: Mini-Project: Creating a Simple Menu with a while Loop

In Post #32, we learned about the dangers of infinite loops. But what if we could harness that “run forever” power and put it under our control? Many applications, like games or command-line tools, need to run continuously, waiting for user commands, until the user specifically decides to quit.

In this mini-project, we will build exactly that: a simple, interactive menu program. We’ll use a while loop that runs as long as the user wants to continue, and an if-elif-else chain to handle their commands. This is a very common and powerful pattern in programming.

Step 1: The Main Loop and the ‘Active’ Flag

Instead of using a counter that increases to a certain number, we will control our loop with a boolean “flag” variable. Let’s call it is_active. Our program’s main loop will continue to run as long as is_active is set to True.

Let’s create the basic skeleton for our program in a new file called menu.py:

# Our "flag" to control the loop
is_active = True

while is_active:
    # All of our menu logic will go inside here
    print("Loop is running... (placeholder)")

    # For now, we'll stop it after one run to test
    is_active = False

print("Program has finished.")

This structure ensures the loop runs at least once and then stops. Now we can start building the real logic inside it.

Step 2: Displaying the Menu and Getting Input

The first thing our program should do inside the loop is show the user their options and ask for their choice. Let’s replace the placeholder content with a menu display and an input() prompt.

is_active = True

while is_active:
    print("\n--- Main Menu ---")
    print("1. Say Hello")
    print("2. Tell a Joke")
    print("3. Exit")

    choice = input("Enter your choice (1-3): ")
    # The if-elif-else logic will go here next

The \n at the start of the menu title is an escape character that prints a newline, giving our menu some nice spacing.

Step 3: Handling the User’s Choice with if-elif-else

Now that we have the user’s choice, we can use an if-elif-else chain, which we mastered in Post #27, to perform the correct action. We will add this logic inside the while loop, right after the input() line.

Python

    # Check the user's choice
    if choice == "1":
        print("\nHello, world!")
    elif choice == "2":
        print("\nWhy don't scientists trust atoms? Because they make up everything!")
    elif choice == "3":
        print("\nExiting the program. Goodbye!")
        is_active = False # This is our terminating condition!
    else:
        print("\nInvalid choice. Please enter a number between 1 and 3.")

Pay close attention to the elif choice == "3": block. When the user chooses to exit, we print a goodbye message and then set is_active = False. This is our user-controlled update step. On the next check at the top of the loop, the while is_active condition will be False, and the loop will terminate gracefully.

The Complete Program

Here is the full, commented script. Run it from your terminal (python3 menu.py) and try all the options. See how the loop continues until you specifically choose to exit.

# Our "flag" to control the loop
is_active = True

# The main loop continues as long as is_active is True
while is_active:
    # Display the menu of options
    print("\n--- Main Menu ---")
    print("1. Say Hello")
    print("2. Tell a Joke")
    print("3. Exit")

    # Get the user's choice
    choice = input("Enter your choice (1-3): ")

    # Use an if-elif-else chain to handle the choice
    if choice == "1":
        print("\nHello, world!")
    elif choice == "2":
        print("\nWhy don't scientists trust atoms? Because they make up everything!")
    elif choice == "3":
        print("\nExiting the program. Goodbye!")
        # Flip the flag to False to exit the loop
        is_active = False
    else:
        # Handle cases where the user enters something other than 1, 2, or 3
        print("\nInvalid choice. Please enter a number between 1 and 3.")

What’s Next?

You’ve successfully built a program that can run indefinitely and respond to different user commands, all controlled by a while loop and a boolean flag. This pattern is the foundation of many interactive applications.

The while loop is excellent for repeating a block of code as long as a condition is true, which is perfect for situations where we don’t know ahead of time how many repetitions are needed. But what if you need to loop through a specific collection of items, like every character in a string? For that, Python has another, often more convenient, type of loop. In Post #34, we will explore the most “Pythonic” loop: the for loop.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment