The most common answer is:
num_of_categories = 3
num_of_question = 3
# Loop for each category
for i in range(num_of_categories):
category_name = input("Enter a category: ")
entries = [] # Initialize an empty list to store entries for each category
# Loop for each question within a category
for j in range(num_of_question):
entry = input(f"Enter something in the category '{category_name}': ")
entries.append(entry) # Append each entry to the list
# Print the category and its entries
print(category_name + ": " + " ".join(entries))
This code will:
- Prompt the user to enter a category name for a predetermined number of categories (
num_of_categories
). - For each category, it will then ask the user to enter items (
num_of_question
times) that belong to that category. - After collecting the items for a category, it prints the category name followed by the items separated by spaces.
This approach uses a list (entries
) to collect items for each category, simplifying the process of adding and displaying items. The join()
method is used to concatenate all items in the list into a single string with spaces in between for printing.
Leave a comment