Array of Namedtuple and menu - Python Programming Exercise

In this exercise, you will develop a Python program that expands the previous exercise (array of NamedTuples), so that it displays a menu where the user can choose to: add data for one point, display all the entered points, calculate (and display) the average values for x and y, or exit the program. This exercise is perfect for practicing the use of NamedTuple and arrays in Python, as well as enhancing your skills in data manipulation and user interaction. By implementing a menu-driven interface, you will gain hands-on experience in handling user input and output in Python. This exercise not only reinforces your understanding of NamedTuple and arrays but also helps you develop efficient coding practices for managing large datasets.

 Category

Arrays, Lists, and Strings

 Exercise

Array Of Namedtuple And Menu

 Objective

Develop a Python program that expands the previous exercise (array of NamedTuples), so that it displays a menu, in which the user can choose to:

- Add data for one point
- Display all the entered points
- Calculate (and display) the average values for x and y
- Exit the program

 Example Python Exercise

 Copy Python Code
from collections import namedtuple

# Define the NamedTuple for a 2D point with color data
Point = namedtuple('Point', ['x', 'y', 'r', 'g', 'b'])

# Create an array to store up to 1000 points
points = []

# Display the menu
while True:
    print("\nMenu:")
    print("1. Add data for one point")
    print("2. Display all entered points")
    print("3. Calculate and display the average values for x and y")
    print("4. Exit")

    # Ask the user to choose an option
    option = input("Choose an option (1, 2, 3, 4): ")

    if option == "1":
        # Add data for one point
        print("Enter the data for a new point:")
        x = int(input("Enter x coordinate (short): "))
        y = int(input("Enter y coordinate (short): "))
        r = int(input("Enter red color value (byte): "))
        g = int(input("Enter green color value (byte): "))
        b = int(input("Enter blue color value (byte): "))

        # Store the new point in the array
        points.append(Point(x, y, r, g, b))
        print("Point added successfully.")

    elif option == "2":
        # Display all entered points
        if points:
            print("\nAll entered points:")
            for i, point in enumerate(points, 1):
                print(f"Point {i}: x: {point.x}, y: {point.y}, r: {point.r}, g: {point.g}, b: {point.b}")
        else:
            print("No points entered yet.")

    elif option == "3":
        # Calculate and display the average values for x and y
        if points:
            avg_x = sum(point.x for point in points) / len(points)
            avg_y = sum(point.y for point in points) / len(points)
            print(f"\nAverage x: {avg_x:.2f}")
            print(f"Average y: {avg_y:.2f}")
        else:
            print("No points entered yet to calculate averages.")

    elif option == "4":
        # Exit the program
        print("Exiting the program.")
        break

    else:
        # Invalid option
        print("Invalid option. Please choose a valid number (1, 2, 3, 4).")

 Output

Menu:
1. Add data for one point
2. Display all entered points
3. Calculate and display the average values for x and y
4. Exit
Choose an option (1, 2, 3, 4): 1
Enter the data for a new point:
Enter x coordinate (short): 5
Enter y coordinate (short): 10
Enter red color value (byte): 255
Enter green color value (byte): 100
Enter blue color value (byte): 50
Point added successfully.

Menu:
1. Add data for one point
2. Display all entered points
3. Calculate and display the average values for x and y
4. Exit
Choose an option (1, 2, 3, 4): 1
Enter the data for a new point:
Enter x coordinate (short): 20
Enter y coordinate (short): 25
Enter red color value (byte): 0
Enter green color value (byte): 255
Enter blue color value (byte): 200
Point added successfully.

Menu:
1. Add data for one point
2. Display all entered points
3. Calculate and display the average values for x and y
4. Exit
Choose an option (1, 2, 3, 4): 2

All entered points:
Point 1: x: 5, y: 10, r: 255, g: 100, b: 50
Point 2: x: 20, y: 25, r: 0, g: 255, b: 200

Menu:
1. Add data for one point
2. Display all entered points
3. Calculate and display the average values for x and y
4. Exit
Choos

 Share this Python Exercise

 More Python Programming Exercises of Arrays, Lists, and Strings

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Library Database

    In this exercise, you will develop a Python program to create a small database for storing book data. For each book, you will keep the following information: Title...

  •  Enhanced Triangle V2

    In this exercise, you will develop a Python program that prompts the user for their name and displays a triangle with it, starting with 1 letter and growing until it ...

  •  Enhanced Rectangle V3

    In this exercise, you will develop a Python program that prompts the user for their name and a size, and displays a hollow rectangle with it. This exercise is ...

  •  Symmetrical Triangle

    In this exercise, you will develop a Python program that displays a centered triangle from a string entered by the user. This exercise is perfect for practicin...

  •  Urban Database

    In this exercise, you will develop a Python program to create a database for storing information about urban areas. In the first approach, you will store only the nam...

  •  Display Banner

    In this exercise, you will develop a Python program to mimic the basic Unix SysV "banner" utility, capable of displaying large texts. This exercise is perfect ...