How to Design a Program to Record and Search Titles with Sentences in Python
You can design the program using a dictionary data structure where the title is the key and the sentence after the title is the value. Here are the steps to implement the program:
- Create an empty dictionary to store the titles and sentences.
- Prompt the user to enter a title and the sentence after the title.
- Add the title and the sentence as a key-value pair in the dictionary.
- Repeat steps 2 and 3 until the user is done entering titles and sentences.
- Prompt the user to enter a title to search for.
- Check if the searched title exists in the dictionary.
- If the title exists, print the sentence after the title.
- If the title does not exist, print a message indicating that the title was not found.
Here is an example code in Python:
# Step 1
records = {}
# Step 2-4
while True:
title = input('Enter a title (or 'done' to stop): ')
if title == 'done':
break
sentence = input('Enter the sentence after the title: ')
records[title] = sentence
# Step 5
search_title = input('Enter a title to search for: ')
# Step 6-8
if search_title in records:
print(records[search_title])
else:
print(f'{search_title} not found')
In this example, the program prompts the user to enter a title and a sentence, and adds them to the records dictionary using title as the key and sentence as the value. The program continues to prompt for titles and sentences until the user enters 'done'.
Then, the program prompts the user to enter a title to search for, and checks if the title exists in the records dictionary. If it does, the program prints the sentence after the title. If it does not, the program prints a message indicating that the title was not found.
原文地址: https://www.cveoy.top/t/topic/oqgH 著作权归作者所有。请勿转载和采集!