Python+SQLite3在线图书馆开发问题求助:函数内循环退出异常与作者搜索功能实现
Hey Hugo, let's work through your two library system issues step by step to get everything working as you want!
1. Fixing the Search Loop & Returning to Main Menu
First, let's clarify how to exit a loop inside a function and get back to the main program:
breakstatement: This exits the immediate loop it's in. Once the loop ends, the function finishes executing and returns control to the main menu automatically.returnstatement: If you want to exit the entire function right away (even from nested loops), usereturn— it stops the function immediately and sends you back to the main program.- Flag variable: You can use a boolean variable (like
keep_searching = True) as your loop condition, then set it toFalsewhen you want to exit.
Looking at your current search function, the extra break at the end of the loop makes it exit after one search. If you want to let users search multiple times until they choose to return, remove that final break and let the loop run until they input FIN. Here's the adjusted logic:
def search(): try: with connection() as conn: cursor = conn.cursor() while True: recherche = input("Quel livre recherchez-vous (tapez 'FIN' pour retourner au menu) : ") if recherche.upper() == 'FIN': break # Exit the loop and return to main menu # Run search query sql = "select id_livre, titre_livre, auteur_livre from Livres where titre_livre like ?" cursor.execute(sql, (f'%{recherche}%',)) # Use % before/after to match partial titles lignes = cursor.fetchall() if not lignes: print("Aucun livre trouvé avec ce terme.") else: for ligne in lignes: print(f"ID: {ligne[0]} | Titre: {ligne[1]} | Auteur: {ligne[2]}") # No break here — loop continues for next search or exit except Exception as e: print(f'Erreur lors de la recherche : {e}')
2. Extending Search to Support Author Queries
To let users choose between searching by title or author, we'll add a quick selection step at the start of the search function. Then we'll run different SQL queries based on their choice. Here's how to implement it:
def search(): try: with connection() as conn: cursor = conn.cursor() while True: # Show search options print("\n--- Options de Recherche ---") print("1. Rechercher par titre") print("2. Rechercher par auteur") print("3. Retourner au menu principal") choix = input("Votre choix : ") if choix == '3': break # Return to main menu if choix not in ['1', '2']: print("Choix invalide, veuillez réessayer.") continue # Get search term terme = input("Entrez votre terme de recherche : ").strip() if not terme: print("Le terme de recherche ne peut pas être vide.") continue # Run appropriate query if choix == '1': sql = "select id_livre, titre_livre, auteur_livre from Livres where titre_livre like ?" param = (f'%{terme}%',) else: sql = "select id_livre, titre_livre, auteur_livre from Livres where auteur_livre like ?" param = (f'%{terme}%',) cursor.execute(sql, param) lignes = cursor.fetchall() # Display results if not lignes: print("Aucun livre trouvé.") else: print("\nLivres trouvés :") for ligne in lignes: print(f"ID: {ligne[0]} | Titre: {ligne[1]} | Auteur: {ligne[2]}") except Exception as e: print(f'Erreur lors de la recherche : {e}')
Full Modified Code
Here's the complete updated code with both fixes, plus some small improvements like clearer error messages and better output formatting:
import sqlite3 import os dossier_actuel = os.path.dirname(os.path.abspath(__file__)) chemin_base_donnees = os.path.join(dossier_actuel, "bibliotheque.db") def connection(): return sqlite3.connect(chemin_base_donnees) def crea_biblio(): try: with connection() as conn: cursor = conn.cursor() sql = '''CREATE TABLE IF NOT EXISTS Livres ( id_livre INTEGER PRIMARY KEY AUTOINCREMENT, titre_livre TEXT, auteur_livre TEXT );''' cursor.execute(sql) conn.commit() except Exception as e: print(f"Erreur lors de la création de la table : {e}") def ajout_livre(): try: with connection() as conn: cursor = conn.cursor() title = input("Quel est le titre du nouveau livre : ").strip() author = input("Qui est l'auteur : ").strip() if not title or not author: print("Le titre et l'auteur ne peuvent pas être vides.") return sql = "INSERT INTO Livres (titre_livre, auteur_livre) VALUES (?, ?);" cursor.execute(sql, (title, author)) conn.commit() print(f"Livre '{title}' ajouté avec succès !") except Exception as e: print(f"Erreur lors de l'ajout du livre : {e}") def supp_livre(): try: with connection() as conn: cursor = conn.cursor() nom = input("Quel est le titre du livre à supprimer : ").strip() if not nom: print("Le titre ne peut pas être vide.") return # Check if book exists first cursor.execute("SELECT * FROM Livres WHERE titre_livre like ?", (f'%{nom}%',)) if not cursor.fetchall(): print("Aucun livre trouvé avec ce titre.") return sql = '''DELETE FROM Livres WHERE titre_livre like ?;''' cursor.execute(sql, (f'%{nom}%',)) conn.commit() print(f"Livre '{nom}' supprimé avec succès !") except Exception as e: print(f'Erreur lors de la suppression du livre : {e}') def view(): try: with connection() as conn: cursor = conn.cursor() cursor.execute("SELECT id_livre, titre_livre, auteur_livre FROM Livres ORDER BY id_livre") lignes = cursor.fetchall() if not lignes: print("La bibliothèque est vide.") return print("\n--- Votre Bibliothèque ---") for ligne in lignes: print(f"ID: {ligne[0]} | Titre: {ligne[1]} | Auteur: {ligne[2]}") except Exception as e: print(f'Erreur lors de l\'affichage de la bibliothèque : {e}') def search(): try: with connection() as conn: cursor = conn.cursor() while True: print("\n--- Options de Recherche ---") print("1. Rechercher par titre") print("2. Rechercher par auteur") print("3. Retourner au menu principal") choix = input("Votre choix : ") if choix == '3': break if choix not in ['1', '2']: print("Choix invalide, veuillez réessayer.") continue terme = input("Entrez votre terme de recherche : ").strip() if not terme: print("Le terme de recherche ne peut pas être vide.") continue if choix == '1': sql = "select id_livre, titre_livre, auteur_livre from Livres where titre_livre like ?" param = (f'%{terme}%',) else: sql = "select id_livre, titre_livre, auteur_livre from Livres where auteur_livre like ?" param = (f'%{terme}%',) cursor.execute(sql, param) lignes = cursor.fetchall() if not lignes: print("Aucun livre trouvé.") else: print("\nLivres trouvés :") for ligne in lignes: print(f"ID: {ligne[0]} | Titre: {ligne[1]} | Auteur: {ligne[2]}") except Exception as e: print(f'Erreur lors de la recherche : {e}') # Main program loop if __name__ == "__main__": crea_biblio() # Initialize database once at start while True: print("\n--- Menu Principal ---") choice = input("Voulez-vous (1) ajouter un livre, (2) supprimer un livre, (3) voir la bibliothèque, (4) rechercher un livre, ou (q) quitter ? ") if choice == "1": ajout_livre() elif choice == "2": supp_livre() elif choice == "3": view() elif choice == "4": search() elif choice.lower() == "q": print("Au revoir !") break else: print("Choix invalide, veuillez réessayer.")
内容的提问来源于stack exchange,提问作者Hugo

