Python搜索函数逻辑错误排查:无法正常执行搜索及退出循环
search_counties Function Issues Let's break down the problems in your code and fix them step by step—you've got a few logical missteps causing the infinite loop and broken search functionality.
Key Problems in the Original Code
Infinite Loop Condition
Yourwhileloop usesorinstead ofand:while search != 'q' or search != 'quit':This condition will always be true—no input can be equal to both 'q' and 'quit' at the same time. So the loop never exits, even when you enter valid quit commands.
Broken Search Logic
- You're checking
search in counties, butcountiesis a list of dictionaries, not strings. This will never match unless your search term is literally one of the dictionary objects (which it never will be). - The
for i in countiesloop definesibut never uses it—you meant to iterate over each county dictionary and check against its data. - The input prompt is placed inside the loop in a way that causes it to repeat endlessly, even before a search attempt is made.
- You're checking
Redundant & Misplaced Exit Check
You have anif search == 'q' or search == 'quit': sys.exit()inside the loop, but the loop condition already should exclude these values. This check is unnecessary and out of place.
Fixed Code
Assuming your county dictionaries have a key like 'name' (adjust this to match your actual dictionary structure) that stores the county name, here's the corrected function:
import sys def search_counties(counties): while True: # Use an infinite loop we control explicitly search = input('Search: ').strip().lower() # Handle exit first for clarity if search in {'q', 'quit'}: sys.exit() # Perform the search across counties found_matches = False for county in counties: # Check if search term exists in the county's name (case-insensitive) if search in county['name'].lower(): print_county(county) found_matches = True # Inform user if no results were found if not found_matches: print("No counties matching your search were found.")
What Changed & Why
- Simplified Loop Flow: Using
while Truemakes the code easier to follow—we handle exit logic right at the start of each loop iteration. - Proper Exit Handling: Checking
search in {'q', 'quit'}is cleaner than multipleorconditions, and we exit immediately when valid quit terms are entered. - Fixed Search Logic: We iterate over each
countyincounties, check if the search term exists in the county's name (converted to lowercase for case-insensitive matching), and callprint_countyfor matches. - Match Tracking: The
found_matchesflag lets us inform the user when no results are found, instead of silently looping back. - Input Cleaning: Added
.strip()to remove accidental leading/trailing whitespace from user input.
Notes for Your Use Case
- Replace
county['name']with the actual key in yourcountydictionaries that holds the county name (e.g.,county['county_name']if that's what you're using). - To search other fields (like poverty rates), extend the condition to check multiple keys:
if search in county['name'].lower() or search in str(county['poverty_rate']).lower():
内容的提问来源于stack exchange,提问作者staz

