You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中完成子函数后如何返回菜单函数?附电影程序代码问题

Fixing Your Python Movie Manager Issues: Returning to Main Menu & Year Validation

Hey there! Let's tackle those two issues with your movie management program step by step. I've gone through your code, identified the root problems, and put together a fixed version with extra quality-of-life improvements.

Modified Full Code

import sys
import random
import os

movies = []

def menu():
    print("Welcome to 'The Movie Program!!'")
    print("(A)dd movie to your list")
    print("(L)ist movies you've added")
    print("(S)earch for movies in your list")
    print("(Q)uit the program")  # Added clear quit option
    user_input = input("Which function would you like to do?:\n\nSelection: ").capitalize()
    
    while user_input != 'Q':
        if user_input == 'A':
            add_movies()
        elif user_input == 'L':
            show_movies()
        elif user_input == 'S':
            search_movies()  # Fixed duplicate 'A' check here
        else:
            print("\n\n--Unknown command--Please try again.\n")
        
        # Re-prompt for input after each action to stay in main menu
        print("\n--- Back to Main Menu ---")
        print("(A)dd movie to your list")
        print("(L)ist movies you've added")
        print("(S)earch for movies in your list")
        print("(Q)uit the program")
        user_input = input("\nSelection: ").capitalize()

def add_movies():
    name = input('What is the title of the movie?: ').title()
    director = input("Who was the director of this movie?: ").title()
    
    year = None
    while year is None:
        try:
            year_input = input("What was the release year?: ")
            year = int(year_input)
            # Optional: Add sanity check for valid release year
            if year < 1888:  # First public movie was released in 1888
                print("Please enter a valid year (1888 or later).")
                year = None
        except ValueError:
            print("Oops, only numbers are allowed for the year. Try again!")
    
    # Add the movie to the list once all inputs are valid
    movies.append({
        "name": name,
        "director": director,
        "year": year
    })
    print(f"✅ Successfully added '{name}' to your movie list!")

def show_movies():
    if not movies:
        print("You haven't added any movies yet! Start by adding one with (A)!")
        return
    
    print("\n📽️ Your Movie List:")
    for idx, movie in enumerate(movies, 1):
        print(f"\nMovie {idx}:")
        print(f"Name: {movie['name']}")
        print(f"Director: {movie['director']}")
        print(f"Release Year: {movie['year']}")

def search_movies():
    if not movies:
        print("No movies to search yet! Add some first with (A).")
        return
    
    search_term = input("Enter a movie name or director to search: ").lower()
    found_movies = [
        movie for movie in movies 
        if search_term in movie['name'].lower() or search_term in movie['director'].lower()
    ]
    
    if found_movies:
        print(f"\n🔍 Found {len(found_movies)} matching movie(s):")
        for idx, movie in enumerate(found_movies, 1):
            print(f"\nResult {idx}:")
            print(f"Name: {movie['name']}")
            print(f"Director: {movie['director']}")
            print(f"Release Year: {movie['year']}")
    else:
        print("No movies matched your search term. Try another keyword!")

menu()

Key Fixes & Explanations

1. Fixed Main Menu Navigation

  • Removed recursive menu() call: Your original code was calling menu() inside the while loop, which created nested menu instances and made it impossible to properly return to the main menu. Now we re-prompt for input directly within the same loop.
  • Fixed duplicate menu check: You had two elif user_input == 'A' lines; changed one to 'S' to properly trigger the search function.
  • Added clear quit option: Your loop checked for 'Q' but didn't display it, so now users know they can exit with (Q).

2. Fixed Year Validation & Movie Addition

  • Removed premature return year: This line was exiting the add_movies() function before the movie could be added to the movies list. Now we only proceed to append the movie once a valid year is confirmed.
  • Robust year validation: Used a year = None flag to loop until the user enters a valid integer. Added an optional sanity check for reasonable release years to prevent nonsensical inputs.
  • Success feedback: Added a confirmation message so users know their movie was added successfully.

3. Extra Quality-of-Life Improvements

  • Empty list handling: All functions now check if the movies list is empty and display friendly messages instead of throwing errors.
  • Cleaner output: Redesigned show_movies() to be more readable with numbering and clear section headers.
  • Functional search: Implemented basic search functionality (since your original code marked it as incomplete) that searches by movie name or director.

内容的提问来源于stack exchange,提问作者EasyC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:03:07