Python电影时长范围查询函数异常:跨位数查询无结果
Hey Patrick, I see exactly what's going on here! Let's break down the problem and fix it.
The Root Cause
Your current code is comparing strings instead of numeric values for the movie duration. When you read the lasting value from your film.txt file, it's stored as a string in the dictionary, and the input values you get from input() are also strings.
String comparison works character-by-character based on ASCII values. For example:
"90">"120"because the first character"9"has a higher ASCII value than"1"- This means when you enter a 2-digit min and 3-digit max, none of your movie durations will pass the
r["lasting"] >= lasting_min and r["lasting"] <= lasting_maxcheck—even if their numeric value is in range!
When both min and max are the same number of digits, string comparison happens to line up with numeric comparison (e.g., "80" < "90"), which is why that case works.
The Fix
We just need to convert all duration values to integers before comparing them. Here's the modified version of your lasting() function with key changes highlighted:
def lasting(): x=False # Convert input values to integers with error handling try: lasting_min = int(input("Input minimal lasting: ")) lasting_max = int(input("Input maximal lasting: ")) except ValueError: print("Please enter valid numeric values for duration!") return for r in list_of_movies: # Convert stored duration string to integer for comparison movie_duration = int(r["lasting"]) if movie_duration >= lasting_min and movie_duration <= lasting_max: print() print("Name of the movie: ", r["name"]) print("Genre: ", r["genre"]) print("Lasting: ",r["lasting"],"minutes") print("Director: ", r["director"]) print("Main roles: ", r["main role"]) print("Country: ", r["country"]) print("Year: ", r["year"]) print("-------------------------------") x=True if x==True: print() else: print() print("No movie was found. ") print()
Key Changes:
- Added
int()conversion for user input values, wrapped in atry/exceptblock to handle non-numeric inputs (prevents crashes and gives clear feedback) - Converted the stored
r["lasting"]string to an integer before comparing it to the min/max values
Optional Extra: Input Validation
The try/except block is a small touch to make your code more robust. If someone enters something like "abc" instead of a number, the code will catch the error and prompt them to enter valid numbers instead of crashing.
内容的提问来源于stack exchange,提问作者Patrick Jane

