万卷网 > 题目详情
题型:编程题

管理电话号码

编写一个使用SQLite管理电话号码的程序,功能有:显示所有电话号码、添加、删除和退出,请补全程序。

(本题无需运行通过,写入代码即可)

import sqlite3
def init_db():
    conn = sqlite3.connect('phonebook.db')
    cursor = conn.cursor()
    cursor.execute("DROP TABLE IF EXISTS contacts")
    cursor.execute('''CREATE TABLE contacts (name TEXT NOT NULL,phone TEXT PRIMARY KEY)''')
    conn.commit()
    return conn
def show_all_contacts(conn):
    cursor = conn.cursor()
    cursor.execute("SELECT name, phone FROM contacts ORDER BY name")
    contacts = cursor.        ①        
    if not contacts:
        print("电话簿为空")
        return    
    for name, phone in contacts:
        print(f"{name}: {phone}")
def add_contact(conn):
    name = input("请输入姓名: ").strip()
    phone = input("请输入电话号码: ").strip()    
    if not name or not phone:
        print("错误: 姓名和电话都不能为空")
        return    
    try:
        cursor = conn.cursor()
        cursor.execute("INSERT INTO contacts (name, phone) VALUES (?, ?)", (        ②        ,         ③        ))
        conn.commit()
        print(f"成功添加联系人: {name} - {phone}")
    except sqlite3.IntegrityError:
        print("错误: 该电话号码已存在")
def delete_contact(conn):
    phone = input("请输入要删除的电话号码: ").strip()    
    if not phone:
        print("错误: 请输入有效的电话号码")
        return    
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM contacts WHERE phone=?", (phone,))
    result = cursor.        ④        
    if not result:
        print("错误: 未找到该电话号码")
        return    
    confirm = input(f"确定要删除 {result[0]}({phone}) 吗? (y/n): ").lower()
    if confirm == 'y':
        cursor.execute("DELETE FROM contacts WHERE phone=?", (phone,))
        conn.commit()
        print("联系人已删除")
    else:
        print("取消删除")
# 主程序
def main():
    conn = init_db()    
    while True:
        print("----------------")
        show_all_contacts(conn)
        print("\n请选择操作:")
        print("1. 添加联系人")
        print("2. 删除联系人")
        print("0. 退出程序")        
        choice = input("请输入选项(0-2): ").strip()        
        if choice == "1":
            add_contact(conn)
        elif choice == "2":
            delete_contact(conn)
        elif choice == "0":
            print("\n感谢使用电话簿管理系统,再见!")
            conn.close()
            break
        else:
            print("无效输入,请重新选择!")        
if __name__ == "__main__":
    main()
更新时间:2025-07-25 12:41:38 |
【知识点】 电子学会Python六级

相似题推荐

单选题

下列Python代码使用Matplotlib库绘制了一个什么样的图形?( )

import matplotlib.pyplot as plt  
x = [1, 2, 3, 4, 5]  
y = [1, 4, 9, 16, 25]  
plt.plot(x, y)  
plt.show()
A.

散点图

B.

折线图

C.

直方图

D.

饼图

2026-07-10
单选题

在Python中使用numpy.arange(5)创建数组,得到的结果是?( )

A.

[0 1 2 3 4 5]

B.

[1 2 3 4 5]

C.

[0 1 2 3 4]

D.

[5]

2026-07-10
单选题

下面代码的运行后输出JSON文件内容正确的是?( )

import json
stu = [{'name':“John”,'sex':“man”,“地址”:“渥太华”}]

以Open(“stu.json”, “W”)作为输出文件:

 json.dump(stu, outfile)

A.

[{'姓名':'约翰','性别':'男人','地址':'渥太华'}]

B.

{'名字':'约翰','性别':'男人','地址':'渥太华'}

C.

['名字':'约翰','性别':'男人','地址':'渥太华']

D.

{['名字':'约翰','性别':'男人','地址':'渥太华']}

2026-07-10
判断题

在Python中,要想将一个字符串写入一个文件,可以使用write方法,例如f.write('Hello, world!')。( )

A.正确 B.错误
2026-07-10
单选题

李华正在开发一个图书管理系统,使用SQLite数据库来存储图书信息。他需要编写代码来查询数据库,并根据不同的需求获取查询结果。假设他已经执行了一个查询语句来选择图书表(books)中的所有记录。现在,他面临三种不同的情况,每种情况需要使用不同的方法来获取数据:
1.获取查询结果的第一条记录。
2.获取查询结果的前三条记录。
3.获取查询结果中的所有记录。
请问,李华应该分别使用哪个游标对象的方法来满足上述每种情况的需求?( )

A.

fetchall()[0],fetchall[:3],fetchall()

B.

fetchfirst(),fetchfirst(3),fetchall()

C.

fetchone(),fetchmany(3),fetchall()

D.

getone(),getmany(3),getall()

2026-07-10
公众号
客服 反馈
顶部