From 8210c0fd9e0e2101f25633cae9550d8ba39f1d26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BA=84=E6=80=BF?= <2840415708@qq.com> Date: Wed, 24 Jun 2026 14:56:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...56\345\272\223\345\237\272\347\241\200.md" | 0 ...06\346\236\220\345\205\245\351\227\250.md" | 0 ...00\345\217\221\345\205\245\351\227\250.md" | 0 ...73\345\275\225\347\216\257\350\212\202.md" | 55 +++ ...56\345\272\223\350\277\236\346\216\245.md" | 84 ++++ "38 \345\272\204\346\200\277/20260618 .md" | 145 ++++++ ...1\347\233\256\345\274\200\345\217\2213.md" | 53 ++ ...57\345\242\203\344\275\234\344\270\232.md" | 75 --- ...60\346\215\256\347\261\273\345\236\213.md" | 83 ---- ...47\345\210\266\347\273\223\346\236\204.md" | 123 ----- ...74\345\220\210\350\256\255\347\273\203.md" | 124 ----- ...02\345\270\270\345\244\204\347\220\206.md" | 463 ------------------ ...42\345\220\221\345\257\271\350\261\241.md" | 153 ------ ...15\344\275\234\344\275\234\344\270\232.md" | 98 ---- python-basics/README.md | 4 - 15 files changed, 337 insertions(+), 1123 deletions(-) rename "python-basics/38 \345\272\204\346\200\277/20260609 sqlite\346\225\260\346\215\256\345\272\223\345\237\272\347\241\200.md" => "38 \345\272\204\346\200\277/20260609 sqlite\346\225\260\346\215\256\345\272\223\345\237\272\347\241\200.md" (100%) rename "python-basics/38 \345\272\204\346\200\277/20260610 pandas\346\225\260\346\215\256\345\210\206\346\236\220\345\205\245\351\227\250.md" => "38 \345\272\204\346\200\277/20260610 pandas\346\225\260\346\215\256\345\210\206\346\236\220\345\205\245\351\227\250.md" (100%) rename "python-basics/38 \345\272\204\346\200\277/20260611 streamlit\345\272\224\347\224\250\345\274\200\345\217\221\345\205\245\351\227\250.md" => "38 \345\272\204\346\200\277/20260611 streamlit\345\272\224\347\224\250\345\274\200\345\217\221\345\205\245\351\227\250.md" (100%) create mode 100644 "38 \345\272\204\346\200\277/20260616 \347\231\273\345\275\225\347\216\257\350\212\202.md" create mode 100644 "38 \345\272\204\346\200\277/20260617 \346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" create mode 100644 "38 \345\272\204\346\200\277/20260618 .md" create mode 100644 "38 \345\272\204\346\200\277/20260623 \351\241\271\347\233\256\345\274\200\345\217\2213.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260520 Python\350\257\255\350\250\200\344\270\216\347\216\257\345\242\203\344\275\234\344\270\232.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260521 Python\345\237\272\346\234\254\350\257\255\346\263\225\344\270\216\346\225\260\346\215\256\347\261\273\345\236\213.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260526 Python\346\216\247\345\210\266\347\273\223\346\236\204.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260527 \345\270\270\347\224\250\346\225\260\346\215\256\347\273\223\346\236\204\347\273\274\345\220\210\350\256\255\347\273\203.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260528.\345\207\275\346\225\260\346\250\241\345\235\227\344\270\216\345\274\202\345\270\270\345\244\204\347\220\206.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260602 \351\235\242\345\220\221\345\257\271\350\261\241.md" delete mode 100644 "python-basics/38 \345\272\204\346\200\277/20260603 \346\226\207\344\273\266\346\223\215\344\275\234\344\275\234\344\270\232.md" delete mode 100644 python-basics/README.md diff --git "a/python-basics/38 \345\272\204\346\200\277/20260609 sqlite\346\225\260\346\215\256\345\272\223\345\237\272\347\241\200.md" "b/38 \345\272\204\346\200\277/20260609 sqlite\346\225\260\346\215\256\345\272\223\345\237\272\347\241\200.md" similarity index 100% rename from "python-basics/38 \345\272\204\346\200\277/20260609 sqlite\346\225\260\346\215\256\345\272\223\345\237\272\347\241\200.md" rename to "38 \345\272\204\346\200\277/20260609 sqlite\346\225\260\346\215\256\345\272\223\345\237\272\347\241\200.md" diff --git "a/python-basics/38 \345\272\204\346\200\277/20260610 pandas\346\225\260\346\215\256\345\210\206\346\236\220\345\205\245\351\227\250.md" "b/38 \345\272\204\346\200\277/20260610 pandas\346\225\260\346\215\256\345\210\206\346\236\220\345\205\245\351\227\250.md" similarity index 100% rename from "python-basics/38 \345\272\204\346\200\277/20260610 pandas\346\225\260\346\215\256\345\210\206\346\236\220\345\205\245\351\227\250.md" rename to "38 \345\272\204\346\200\277/20260610 pandas\346\225\260\346\215\256\345\210\206\346\236\220\345\205\245\351\227\250.md" diff --git "a/python-basics/38 \345\272\204\346\200\277/20260611 streamlit\345\272\224\347\224\250\345\274\200\345\217\221\345\205\245\351\227\250.md" "b/38 \345\272\204\346\200\277/20260611 streamlit\345\272\224\347\224\250\345\274\200\345\217\221\345\205\245\351\227\250.md" similarity index 100% rename from "python-basics/38 \345\272\204\346\200\277/20260611 streamlit\345\272\224\347\224\250\345\274\200\345\217\221\345\205\245\351\227\250.md" rename to "38 \345\272\204\346\200\277/20260611 streamlit\345\272\224\347\224\250\345\274\200\345\217\221\345\205\245\351\227\250.md" diff --git "a/38 \345\272\204\346\200\277/20260616 \347\231\273\345\275\225\347\216\257\350\212\202.md" "b/38 \345\272\204\346\200\277/20260616 \347\231\273\345\275\225\347\216\257\350\212\202.md" new file mode 100644 index 0000000..cbb3b41 --- /dev/null +++ "b/38 \345\272\204\346\200\277/20260616 \347\231\273\345\275\225\347\216\257\350\212\202.md" @@ -0,0 +1,55 @@ +``` +# 登录 +import streamlit as st + +st.set_page_config(page_title="登录系统", page_icon="🔐") + +if 'logged_in' not in st.session_state: + st.session_state.logged_in = False # 初始化登录 + +if 'username' not in st.session_state: + st.session_state.username = "" # 初始化为空 + +if not st.session_state.logged_in: + st.title("图书管理系统") + st.subheader("用户登录") + + # 在登录界面添加一个链接文字 `"还没有账号?点击注册"` + st.link_button("还没有账号?点击注册", url="#") + + # 输入框 + username = st.text_input("用户名") + password = st.text_input("密码",type="password") + + # 登录按钮 + if st.button("登录"): + ## 练习3:增加账号在代码中添加一个新账号 `xiaoming`,密码 `123` + if (username == "admin" and password == "admin") or (username == "xiaoming" and password == "123"): + # 登录成功 + st.session_state.logged_in = True + st.session_state.username = username + st.success(f"你好,{username}! 欢迎使用图书管理系统") + st.rerun() + + else: + st.error("用户名或密码错误!") + + +else: + st.title("图书管理系统") + # 让登录后显示 `"你好,[用户名]!欢迎使用图书管理系统"` + st.success(f"欢迎你,{st.session_state.username}!") + + # 退出按钮 + if st.button("退出"): + st.session_state.logged_in = False + st.session_state.username = "" + st.rerun() + # 预留位置给后续功能 + st.info("图书管理功能陆续开发中...") + +``` + +![image-20260616170629057](C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20260616170629057.png) + +![image-20260616170705668](C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20260616170705668.png) \ No newline at end of file diff --git "a/38 \345\272\204\346\200\277/20260617 \346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" "b/38 \345\272\204\346\200\277/20260617 \346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" new file mode 100644 index 0000000..a14af89 --- /dev/null +++ "b/38 \345\272\204\346\200\277/20260617 \346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" @@ -0,0 +1,84 @@ +``` +import streamlit as st +import pandas as pd +import sqlite3 + +# ====== 页面设置 ====== +st.set_page_config(page_title="图书管理系统", page_icon="📚") + +# ====== 初始化登录状态 ====== +if 'logged_in' not in st.session_state: + st.session_state.logged_in = False +if 'username' not in st.session_state: + st.session_state.username = "" + + +# ====== 数据库操作函数 ====== +def get_books(): + """从数据库读取所有图书""" + try: + conn = sqlite3.connect('library.db') + cursor = conn.cursor() + conn.execute("SELECT id, title, author, quantity FROM books") + data = conn.fetchall() + conn.close() + columns = ['id', '书名', '作者', '数量'] + return pd.DataFrame(data, columns=columns) + except Exception as e: + st.error(f"数据库连接失败:{e}") + return pd.DataFrame() + + +# ====== 显示图书列表 ====== +def show_books(): + st.title("📖 图书列表") + + df = get_books() + + if len(df) > 0: + st.dataframe(df, use_container_width=True) + + col1, col2, col3 = st.columns(3) + col1.metric("📚 图书总数", len(df)) + col2.metric("👤 作者数", len(df['作者'].unique())) + col3.metric("📦 总库存", df['数量'].sum()) + else: + st.info("📭 暂无图书,请先运行 init_db.py 初始化数据库") + + +# ====== 登录界面 ====== +if not st.session_state.logged_in: + st.title("📚 图书管理系统") + st.subheader("用户登录") + + username = st.text_input("用户名") + password = st.text_input("密码", type="password") + + if st.button("登录"): + if username == "admin" and password == "admin": + st.session_state.logged_in = True + st.session_state.username = username + st.success("✅ 登录成功!") + st.rerun() + else: + st.error("❌ 用户名或密码错误!") + + st.info("💡 测试账号:admin / admin") + +# ====== 主页面 ====== +else: + st.sidebar.title(f"欢迎,{st.session_state.username}") + + menu = st.sidebar.selectbox( + "选择功能", + ["📖 查看图书", "🚪 退出"] + ) + + if menu == "📖 查看图书": + show_books() + elif menu == "🚪 退出": + st.session_state.logged_in = False + st.session_state.username = "" + st.rerun() +``` + diff --git "a/38 \345\272\204\346\200\277/20260618 .md" "b/38 \345\272\204\346\200\277/20260618 .md" new file mode 100644 index 0000000..3a619d8 --- /dev/null +++ "b/38 \345\272\204\346\200\277/20260618 .md" @@ -0,0 +1,145 @@ +``` +import streamlit as st +import pandas as pd +import sqlite3 + +st.set_page_config( + page_title="图书管理系统", + page_icon="📚", + layout="wide" +) + +if 'logged_in' not in st.session_state: + st.session_state.logged_in = False + + +def init_database(): + conn = sqlite3.connect('library.db') + conn.execute(''' + CREATE TABLE IF NOT EXISTS books( + id INTEGER PRIMARY key AUTOINCREMENT, + title TEXT NOT NULL, + author TEXT NOT NULL, + quantity INTEGER DEFAULT + ) + ''') + conn.commit() + conn.close() + print("✅ 数据库初始化完成") + +def get_all_books(): + conn = sqlite3.connect('library.db') + rows = conn.execute('SELECT * FROM books').fetchall() + date = pd.DataFrame(rows, columns=['编号','书号','作者','库存数量']) + conn.close() + return date + +def insert_sample_data(): + conn = sqlite3.connect('library.db') + count = conn.execute("SELECT COUNT(*) FROM books").fetchone()[0] + + if count == 0: + sample_books = [ + ('三国演义','罗贯中',10), + ('红楼梦','曹雪芹',8), + ('西游记','吴承恩',5) + ] + + for title, author, quantity in sample_books: + conn.execute( + "INSERT INTO books (title, author, quantity) VALUES (?,?,?)" + (title,author,quantity) + ) + + print("✅ 示例数据插入成功") + + conn.commit() + conn.close() +init_database() +insert_sample_data() + +if not st.session_state.logged_in: + + col1, col2, col3, col4, col5= st.columns([1,1,2,1,1]) + with col3: + st.title("📚 图书管理系统") + st.subheader("用户登录") + with st.form("login_form"): + username = st.text_input("用户名",placeholder="请输入用户名") + password = st.text_input("密码",placeholder="请输入密码") + submit = st.form_submit_button("登录",use_container_width=True) + + if submit: + if username == "admin" and password == "admin123": + st.session_state.logged_in = True + st.success("✅ 登录成功!") + st.rerun + else: + st.error("❌ 用户名或密码错误!") + + st.info("💡 测试账号: admin 密码: admin123") + +else: + col1, col2, col3, col4, col5 = st.columns([1,1,2,1,1]) + with col3: + st.title("📚 图书管理系统") + st.success("✅ 欢迎回来!") + + df = get_all_books() + + st.subheader("📖 图书列表") + + if len(df) > 0: + st.dataframe(df,use_column_width=True) + st.caption(f"共 {len(df)} 本图书") + else: + st.info("📭 暂无图书") + + if st.button("退出登录"): + st.session_state.logged_in = False + st.rerun() +``` + +``` +import sqlite3 as db +import pandas as pd + +def init_db(): + conn = db.connect('books.db') + + conn.execute(''' + CREATE TABLE IF NOT EXISTS books ( + id INTEGER PRIMARY key AUTOINCREMENT, + bookname TEXT NOT NULL, + price REAL NOT NULL + ) + ''') + + conn.close() + +def select_db(): + conn = db.connect('books.db') + rows = conn.execute('SELECT * FROM books').fetchall() + data = pd.DataFrame(rows, columns=['id','bookname', 'price']) + conn.close() + return data + +def insert_db(book): + conn = db.connect('books.db') + conn.execute('insert into books (bookname, price) values (?,?)',book) + conn.commit() + conn.close() + +def delete_db(book): + conn = db.connect("books.db") + conn.execute('delete from books where bookname = ?',book) + conn.commit() + conn.close() + +def update_db(book): + conn = db.connect('books.db') + conn.execute('update books set bookname = ?, price = ? where id = ?',book) + conn.commit() + conn.close() +``` + diff --git "a/38 \345\272\204\346\200\277/20260623 \351\241\271\347\233\256\345\274\200\345\217\2213.md" "b/38 \345\272\204\346\200\277/20260623 \351\241\271\347\233\256\345\274\200\345\217\2213.md" new file mode 100644 index 0000000..1b31609 --- /dev/null +++ "b/38 \345\272\204\346\200\277/20260623 \351\241\271\347\233\256\345\274\200\345\217\2213.md" @@ -0,0 +1,53 @@ +``` +import streamlit as st +import pandas as pd +import sqlite3 +# 标题 +st.set_page_config( + page_title="图书管理系统", + page_icon="📚" +) +# 初始化 +if 'logged_in'not in st.session_state: + st.session_state.logged_in = False + +def init_database(): + # 初始化数据库 建立图书表 + + # 连接sqlite数据库 + conn = sqlite3.connect('library.db') + + conn.execute(''' + CREATE TABLE IF NOT EXISTS books( + id INTEGER PRIMARY key AUTOINCREMENT, + title text NOT NULL, + author text NOT NULL, + quantity integer default 1 + ) + ''') + # 提交,保存更改 + conn.commit() + # 关闭数据库 + conn.close() + # 输出提示信息,主要用于调试 + print("数据库初始化成功!") + +def get_all_books(): + """获取图书数据 + + Returns: + pandas.DataFrame: 包含所有图书记录的DataFrame + """ + # 连接数据库 + conn = sqlite3.connect('library.db') + + # 使用pandas的read_sql_query方法执行SQL查询 + # 结果自动转化为DataFrame,方便在streamlit中显示 + df = pd.read_sql_query("SELECT * FROM books ORDER BY id", conn) + + # 关闭连接 + conn.close() + return df + +``` + diff --git "a/python-basics/38 \345\272\204\346\200\277/20260520 Python\350\257\255\350\250\200\344\270\216\347\216\257\345\242\203\344\275\234\344\270\232.md" "b/python-basics/38 \345\272\204\346\200\277/20260520 Python\350\257\255\350\250\200\344\270\216\347\216\257\345\242\203\344\275\234\344\270\232.md" deleted file mode 100644 index 5802b9c..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260520 Python\350\257\255\350\250\200\344\270\216\347\216\257\345\242\203\344\275\234\344\270\232.md" +++ /dev/null @@ -1,75 +0,0 @@ -第七题 - -``` -print('姓名:张三') -print('专业:软件技术') -print('爱好:编程、羽毛球'); -``` - -image-20260520100301547 - -第八题 - -``` -print("====================") -print("课程信息展示程序") -print("====================") -print('课程名称:Python编程基础与应用开发') -print("使用语言:Python") -print('开发工具:PyCharm') -print('学习内容:基础语法、文件处理、sqlite、pandas、streamlit') -print('学习目标:能够使用Python完成基础应用的开发') -print("===================="); -``` - -image-20260520100332068 - -第一题 - -image-20260520100715997 - -第二题 - -``` -print('hello,Python!') -print('我的第一个Python程序'); -``` - -image-20260520101135565 - -第三题 - -解释`` - -.py - -Python解释器 - -print() - -第四题 - -``` -print("姓名:郭紫溪") -print("班级:253") -print("本课程学习目标:掌握基本的Python语言"); -``` - -image-20260520101550031 - -第五题 - -``` -print("课程名称:Python编程基础与应用开发") -print("开发工具:PyCharm") -print("Python版本:3.12.x") -print("本节主题:Python语言概述与开发环境"); -``` - -image-20260520101855179 - -第六题 - -1.在终端调用Python解释器,读取并执行hello.py文件中的代码,运行该Python程序 - -2.PyCharm是代码编辑器/IDE,Python解释器负责执行代码;PyCharm调用解释器完成代码运行 \ No newline at end of file diff --git "a/python-basics/38 \345\272\204\346\200\277/20260521 Python\345\237\272\346\234\254\350\257\255\346\263\225\344\270\216\346\225\260\346\215\256\347\261\273\345\236\213.md" "b/python-basics/38 \345\272\204\346\200\277/20260521 Python\345\237\272\346\234\254\350\257\255\346\263\225\344\270\216\346\225\260\346\215\256\347\261\273\345\236\213.md" deleted file mode 100644 index 8cd770d..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260521 Python\345\237\272\346\234\254\350\257\255\346\263\225\344\270\216\346\225\260\346\215\256\347\261\273\345\236\213.md" +++ /dev/null @@ -1,83 +0,0 @@ -``` -# 输入名字和年龄 -name = input("请输入姓名:") -age = int(input("请输入年龄:")) -# 输入两个整数 -figure = float(input("请输入整数1:")) -digit = float(input("请输入整数2:")) -# 输入商品单价和数量 -price = float(input("请输入商品单价:")) -amount = float(input("请输入商品数量:")) - -#输出名字和年龄 -print(f"姓名:{name}") -print(f"年龄:{age}") - -#输出整数的和、差、积、商 -print(f"和:{figure + digit}") -print(f"差:{figure - digit}") -print(f"积:{figure * digit}") -print(f"商:{figure / digit}") - -#输出商品总价 -total = price * amount -print(f"商品总价:{total}") -``` - -image-20260521205827229 - -1. - -``` -# 输入三门课程成绩,输出总分和平均分。 -chinese = float(input("请输入语文成绩:")) -math = float(input("请输入数学成绩:")) -english = float(input("请输入英语成绩:")) - -#输入圆的半径,计算圆面积,圆周率取 `3.14`。 -radius = float(input("请输入圆的半径:")) -pi = 3.14 - -# 输入身高和体重,计算 BMI -stature = float(input("请输入身高:")) -weight = float(input("请输入体重:")) - -# 输出总分、平均分 -total = chinese + math + english -average = total/3 - -print(f"总分:{total:.2f}") -print(f"平均分:{average}") - -# 输出圆的面积 -area = pi*radius*radius - -print(input(f"圆面积:{area:.2f}")) - -# 输出BMI -BMI = weight/(stature * stature) -print(f"{BMI:BMI:.2f}") -``` - -image-20260521211439619 - -1. - -``` -name = input("请输入商品名称:") -price = float(input("请输入商品单价:")) -count = int(input("请输入购买数量:")) -discount = float(input("请输入优惠金额:")) - -origin_total = price * count -pay_money = origin_total - discount - -print("====== 消费信息 ======") -print(f"商品:{name}") -print(f"原价:{origin_total:.2f} 元") -print(f"优惠:{discount:.2f} 元") -print(f"实付:{pay_money:.2f} 元") -print("======================") -``` - -image-20260521211605386 \ No newline at end of file diff --git "a/python-basics/38 \345\272\204\346\200\277/20260526 Python\346\216\247\345\210\266\347\273\223\346\236\204.md" "b/python-basics/38 \345\272\204\346\200\277/20260526 Python\346\216\247\345\210\266\347\273\223\346\236\204.md" deleted file mode 100644 index 1fc2dfb..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260526 Python\346\216\247\345\210\266\347\273\223\346\236\204.md" +++ /dev/null @@ -1,123 +0,0 @@ -A - -``` -# ### A组:基础必做 -# -# 1. 输入一个成绩,判断是否及格。 -# 2. 输出 1 到 100 的所有整数。 -# 3. 计算 1 到 100 的累加和。 -# 4. 输出 1 到 100 中所有偶数。 - -score = int(input("请输入一个成绩:")) -for i in range(1,101): - print(i,end="") - -total = 0 -for i in range(1,101): - total = total + i -print("1到100的累加和:", total) - -for i in range(2,101,2): - print(i,end="") -``` - -image-20260526163647462 - -B - -``` -# ### B组:巩固提升 -# -# 1. 输入成绩,输出等级:优秀、良好、及格、不及格。 -# 2. 输出九九乘法表。 -# 3. 输入一个整数,判断是否为质数。 -# 4. 输入 5 个成绩,输出平均分。 -score = int(input("请输入成绩:")) -if score >= 90: - print("优秀") -elif score >=80: - print("良好") -elif score >=60: - print("及格") -else: - print("不及格") - -for i in range(1,10): - for j in range(1,i+1): - print(f"{j} * {i} = {i * j}",end="\t") - print() - -num = int(input("输入整数:")) -if num < 2: - print("不是质数") -else: - flag = True - for i in range(2,int(num ** 0.5) + 1): - if num % i == 0: - flag = False - break - print("是质数" if flag else "不是质数") - -s = 0 -for i in range(5): - n = float(input("输入成绩:")) - s += n -avg = s / 5 -print("平均分:",avg) -``` - -image-20260526163516384 - -image-20260526164018970 - -C - -``` -# ### C组:拓展训练 -# -# 1. 编写带次数限制的登录验证程序。 -# 2. 编写猜数字游戏,统计用户猜测次数。 -# 3. 输入若干成绩,以 `-1` 结束,输出最高分、最低分和平均分。 - -pwd = "123456" -pwd = "123456" -count = 3 -while count > 0: - pw = input("请输入密码: ") - if pw == pwd: - print("登录成功") - break - count -= 1 - print(f"密码错误,剩余{count}次机会") -else: - print("次数用尽,禁止登录") - -import random -target = random.randint(1,100) -cnt = 0 -while True: - guess = int(input("猜1-100数字:")) - cnt += 1 - if guess > target: - print("大了!") - elif guess < target: - print("小了!") - else: - print(f"恭喜你猜对了!一共猜了{cnt}次") - break - -scores = [] -while True: - n = float(input("输入成绩(-1结束):")) - if n == -1: - break - scores.append(n) -if scores: - print("最高分:", max(scores)) - print("最低分", min(scores)) - print("平均", sum(scores))/len(scores) -else: - print("未输入有效成绩!") -``` - -image-20260526165343610 \ No newline at end of file diff --git "a/python-basics/38 \345\272\204\346\200\277/20260527 \345\270\270\347\224\250\346\225\260\346\215\256\347\273\223\346\236\204\347\273\274\345\220\210\350\256\255\347\273\203.md" "b/python-basics/38 \345\272\204\346\200\277/20260527 \345\270\270\347\224\250\346\225\260\346\215\256\347\273\223\346\236\204\347\273\274\345\220\210\350\256\255\347\273\203.md" deleted file mode 100644 index 6660e31..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260527 \345\270\270\347\224\250\346\225\260\346\215\256\347\273\223\346\236\204\347\273\274\345\220\210\350\256\255\347\273\203.md" +++ /dev/null @@ -1,124 +0,0 @@ -A - -``` -# ### A组:基础必做 -# -# 1. 创建列表保存 5 个学生姓名并遍历输出。 -name = ["张三","李四","王五","老六","老七"] -for n in name: - print(n) -# 2. 创建字典保存一个学生的姓名、年龄、成绩。 -student = { - "name":"张三", - "age":18, - "score":90 -} -print(student["name"],student["age"],student["score"]) -# 3. 创建集合去除重复课程名称。 -course_list = ["语文","数学","英语","数学","语文","物理"] -course_list = set(course_list) -print("去除重复课程后的课程名称:",course_list) -# 4. 统计列表中元素个数。 -name = ["张三","李四","王五","老六","老七"] -count = len(name) -print("列表元素个数:",count) -``` - -image-20260527101918675 - -image-20260527102329321 - -image-20260527102803825 - -image-20260527103105346 - -B - -``` -#### B组:巩固提升 -#1. 使用列表保存 5 个成绩,计算平均分。 -score = {85,98,60,88,70} -avg = sum(score)/len(score) -print("平均分:",score) -#2. 使用字典保存商品信息,并计算折后价格。 -goods = { - "名称":"电脑", - "原价":10000, - "折扣":0.85 -} -new_price = goods["原价"] * goods["折扣"] -print("折扣后价格",new_price) -#3. 使用列表嵌套字典保存 3 个学生信息并输出。 -student_list = [ - {"姓名":"张三","年龄":18,"分数":80}, - {"姓名":"李四","年龄":19,"分数":88}, - {"姓名":"王五","年龄":18,"分数":85} -] -for student in student_list: - print(student) -#4. 查找最高分学生。 -student_list = [ - {"姓名":"张三","分数":80}, - {"姓名":"李四","分数":88}, - {"姓名":"王五","分数":85} -] -max_stude = max(student_list,key=lambda x:x["分数"]) -print("最高分数学生:",max_stude) -``` - -image-20260527104108899 - -image-20260527104417434 - -image-20260527104756635 - -image-20260527105108958 - -C - -``` -#1. 实现通讯录添加和查询功能。 -phone_book = {} -def add_contact(): - name = input("输入姓名:") - tel = input("输入手机号:") - phone_book[name] = tel - print("添加成功!") -def search_contact(): - name = input("输入查询姓名:") - if name in phone_book: - print(f"手机号:{phone_book[name]}") - else: - print("无该联系人!") - -while True: - op = input("\n1-添加 2-查询 0-退出:") - if op == "1": - add_contact() - elif op == "2": - search_contact() - elif op == "0": - break -#2. 实现购物车总价计算。 -cart = [ - {"name":"牛奶","price":5,"num":2}, - {"name":"面包","price":8,"num":1}, - {"name":"可乐","price":4,"num":3} -] -total = 0 -for item in cart: - total += item["price"] * item["num"] -print("购物车总价:",total) -#3. 统计字符串中每个字符出现次数。 -s = "hello" -char_count = {} -for c in s: - char_count[c] = char_count.get(c, 0) + 1 -print("字符统计:", char_count) -``` - -image-20260527105847775 - -image-20260527110206938 - -image-20260527110348720 \ No newline at end of file diff --git "a/python-basics/38 \345\272\204\346\200\277/20260528.\345\207\275\346\225\260\346\250\241\345\235\227\344\270\216\345\274\202\345\270\270\345\244\204\347\220\206.md" "b/python-basics/38 \345\272\204\346\200\277/20260528.\345\207\275\346\225\260\346\250\241\345\235\227\344\270\216\345\274\202\345\270\270\345\244\204\347\220\206.md" deleted file mode 100644 index cdcd3a7..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260528.\345\207\275\346\225\260\346\250\241\345\235\227\344\270\216\345\274\202\345\270\270\345\244\204\347\220\206.md" +++ /dev/null @@ -1,463 +0,0 @@ -# 第5课 函数、模块与异常处理 - -## 一、知识导入 - -随着程序规模增大,重复代码会降低可读性和维护性。函数用于封装可复用逻辑,模块用于组织代码和复用功能,异常处理用于提升程序面对错误输入或运行异常时的稳定性。 - -## 二、学习目标 - -1. 掌握函数的定义和调用。 -2. 理解参数、返回值、默认参数的作用。 -3. 掌握常用模块的导入方式。 -4. 理解异常的概念和常见异常类型。 -5. 能使用 `try-except` 处理输入错误和文件错误。 -6. 能将函数、模块、异常处理结合到完整程序中。 - -## 三、核心概念 - -| 概念 | 说明 | -| -------- | -------------------------------- | -| 函数 | 封装一段可重复使用的代码 | -| 参数 | 调用函数时传入的数据 | -| 返回值 | 函数执行后返回给调用位置的结果 | -| 模块 | 保存 Python 代码的文件或库 | -| 标准库 | Python 自带的模块集合 | -| 第三方库 | 需要额外安装的模块或包 | -| 异常 | 程序运行时出现的错误 | -| 异常处理 | 捕获并处理异常,避免程序直接终止 | - -![img](https://gitee.com/onesheet/picture-warehouse/raw/master/pic/upgit_20260528_1779972577.png) - -## 四、函数的定义与调用 - -### 1. 函数是什么 - -函数是组织代码的基本单位。将一段具有明确功能的代码写成函数,可以减少重复,提高程序结构清晰度。 - -### 2. 定义函数 - -``` -def greet(): - print("Hello, Python") -``` - -语法格式: - -``` -def 函数名(): - 函数体 -``` - -### 3. 调用函数 - -``` -def greet(): - print("Hello, Python") - - -greet() -``` - -逐行说明: - -``` -def greet(): -``` - -定义名为 `greet` 的函数。 - -``` -print("Hello, Python") -``` - -函数体。调用函数时才会执行。 - -``` -greet() -``` - -调用函数。 - -## 五、函数参数 - -### 1. 位置参数 - -``` -def greet(name): - print(f"你好,{name}") - - -greet("张三") -``` - -`name` 是形参,`"张三"` 是实参。 - -### 2. 多个参数 - -``` -def add(a, b): - result = a + b - print(result) - - -add(3, 5) -``` - -### 3. 关键字参数 - -``` -def introduce(name, age): - print(f"{name},{age}岁") - - -introduce(name="李四", age=18) -``` - -关键字参数可以明确指出参数名,提高可读性。 - -### 4. 默认参数 - -``` -def greet(name, message="你好"): - print(f"{message},{name}") - - -greet("张三") -greet("李四", "欢迎") -``` - -默认参数在调用时可以省略。 - -## 六、返回值 - -### 1. return语句 - -函数可以使用 `return` 返回结果。 - -``` -def add(a, b): - return a + b - - -result = add(3, 5) -print(result) -``` - -逐行说明: - -``` -return a + b -``` - -将计算结果返回给函数调用位置。 - -``` -result = add(3, 5) -``` - -接收函数返回值,并保存到变量 `result`。 - -### 2. 示例:计算平均分 - -``` -def calculate_average(chinese, math, english): - total = chinese + math + english - average = total / 3 - return average - - -avg = calculate_average(86, 92, 78) -print(f"平均分:{avg:.2f}") -``` - -## 七、模块的使用 - -### 1. 模块是什么 - -模块是包含 Python 代码的文件。通过模块,可以复用已有函数、变量和类。 - -### 2. 导入标准库模块 - -``` -import random - -number = random.randint(1, 100) -print(number) -``` - -`random` 是标准库模块,`randint()` 用于生成指定范围内的随机整数。 - -### 3. 导入模块中的指定内容 - -``` -from datetime import datetime - -now = datetime.now() -print(now) -``` - -### 4. 第三方库 - -第三方库需要通过 `pip` 安装。例如: - -``` -pip install requests -``` - -安装后才可以在程序中导入: - -``` -import requests -``` - -## 八、异常处理 - -### 1. 异常是什么 - -异常是程序运行过程中出现的错误。例如: - -``` -age = int(input("请输入年龄:")) -``` - -如果用户输入 `abc`,程序会出现 `ValueError`。 - -### 2. try-except语句 - -``` -try: - age = int(input("请输入年龄:")) - print(age) -except ValueError: - print("年龄必须是整数") -``` - -执行逻辑: - -1. 先执行 `try` 中的代码。 -2. 如果发生 `ValueError`,执行 `except` 中的代码。 -3. 如果没有异常,`except` 不执行。 - -### 3. 常见异常类型 - -| 异常类型 | 常见原因 | -| ------------------- | ---------------- | -| `ValueError` | 类型转换失败 | -| `ZeroDivisionError` | 除数为 0 | -| `FileNotFoundError` | 文件不存在 | -| `KeyError` | 字典中没有指定键 | -| `IndexError` | 列表索引越界 | - -### 4. else和finally - -``` -try: - score = float(input("请输入成绩:")) -except ValueError: - print("成绩必须是数字") -else: - print(f"成绩:{score}") -finally: - print("程序结束") -``` - -`else` 在没有异常时执行,`finally` 无论是否异常都会执行。 - -![img](https://gitee.com/onesheet/picture-warehouse/raw/master/pic/upgit_20260528_1779973962.png) - -## 九、课堂完整案例:安全成绩输入函数 - -### 1. 功能要求 - -封装函数,反复接收成绩输入,直到输入 0 到 100 之间的数字。 - -### 2. 完整代码 - -``` -def read_score(): - while True: - try: - score = float(input("请输入成绩:")) - except ValueError: - print("成绩必须是数字") - continue - - if 0 <= score <= 100: - return score - - print("成绩范围必须是0到100") - - -score = read_score() -print(f"有效成绩:{score}") -``` - -### 3. 逐行代码讲解 - -``` -def read_score(): -``` - -定义读取成绩的函数。 - -``` -while True: -``` - -持续循环,直到得到有效成绩。 - -``` -try: -``` - -尝试执行可能出错的代码。 - -``` -score = float(input("请输入成绩:")) -``` - -接收输入并转换为浮点数。 - -``` -except ValueError: -``` - -如果转换失败,执行异常处理代码。 - -``` -return score -``` - -返回有效成绩,并结束函数。 - -## 十、课堂互动 - -### 互动1:判断函数返回值 - -``` -def add(a, b): - return a + b - - -print(add(2, 3)) -``` - -问题:程序输出什么? - -### 互动2:找出异常类型 - -``` -num = int("abc") -``` - -问题:会出现什么异常? - -### 互动3:补全函数 - -补全函数,返回三个数的最大值: - -``` -def get_max(a, b, c): - # 补全代码 -``` - -## 十一、易错点 - -| 易错点 | 错误示例 | 正确做法 | -| ------------------------ | ----------------------- | ----------------------- | -| 定义函数后未调用 | 只写 `def` | 使用 `函数名()` 调用 | -| 忘记冒号 | `def test()` | `def test():` | -| 参数数量不匹配 | `add(1)` | 按定义传入足够参数 | -| `return` 和 `print` 混淆 | 函数只打印不返回 | 需要结果时使用 `return` | -| 异常范围过大 | 直接 `except Exception` | 优先捕获具体异常 | - -## 十二、分层练习 - -### A组:基础必做 - -1. 定义函数 `add(a, b)`,返回两个数之和。 -2. 定义函数 `is_even(n)`,判断一个整数是否为偶数。 -3. 使用 `random` 生成 1 到 10 的随机数。 -4. 使用 `try-except` 处理年龄输入错误。 - -### B组:巩固提升 - -1. 定义函数计算列表平均值。 -2. 定义函数根据成绩返回等级。 -3. 使用 `datetime` 输出当前日期。 -4. 改写第 3 课猜数字游戏,把输入处理封装成函数。 - -### C组:拓展训练 - -1. 编写函数验证密码强度。 -2. 编写函数统计字符串中数字字符个数。 -3. 编写函数安全读取整数,直到用户输入合法整数。 - -## 十三、小项目任务:函数版成绩管理工具 - -### 1. 项目要求 - -使用函数完成成绩录入、平均分计算、等级判断。 - -### 2. 功能要求 - -1. 封装 `read_score()`,安全读取成绩。 -2. 封装 `calculate_average()`,计算平均分。 -3. 封装 `get_level()`,返回等级。 -4. 主程序调用函数并输出结果。 - -### 3. 参考代码框架 - -``` -def read_score(course_name): - while True: - try: - score = float(input(f"请输入{course_name}成绩:")) - except ValueError: - print("成绩必须是数字") - continue - - if 0 <= score <= 100: - return score - - print("成绩范围必须是0到100") - - -def calculate_average(a, b, c): - return (a + b + c) / 3 - - -def get_level(score): - if score >= 90: - return "优秀" - if score >= 80: - return "良好" - if score >= 60: - return "及格" - return "不及格" - - -chinese = read_score("语文") -math = read_score("数学") -english = read_score("英语") -average = calculate_average(chinese, math, english) -level = get_level(average) - -print(f"平均分:{average:.2f}") -print(f"等级:{level}") -``` - -## 十四、课后基础训练 - -1. 完成 A 组全部练习。 -2. 从 B 组任选 2 题完成。 -3. 完成小项目任务。 -4. 总结函数参数和返回值的区别。 - -## 十五、本课小结 - -1. 函数用于封装可复用代码。 -2. 参数用于向函数传入数据。 -3. 返回值用于将函数结果交给调用位置。 -4. 模块可以复用标准库和第三方库功能。 -5. 异常处理可以提高程序稳定性。 \ No newline at end of file diff --git "a/python-basics/38 \345\272\204\346\200\277/20260602 \351\235\242\345\220\221\345\257\271\350\261\241.md" "b/python-basics/38 \345\272\204\346\200\277/20260602 \351\235\242\345\220\221\345\257\271\350\261\241.md" deleted file mode 100644 index 449a491..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260602 \351\235\242\345\220\221\345\257\271\350\261\241.md" +++ /dev/null @@ -1,153 +0,0 @@ -A - -``` -### A组:基础必做 - -#1. 定义一个 `Dog` 类,包含 `name` 和 `age` 两个属性。 -class Dog: - def __init__(self,name,age): - self.name = name - self.age = age - - def show_info(self): - print(f"狗狗名字:{self.name},年龄:{self.age}岁") - -dog1 = Dog("旺财",3) -dog1.show_info() -dog2 = Dog("乐乐",5) -dog2.show_info() -#面积 -import math -class Circle: - def __init__(self,radius): - self.radius = radius - - def calc_area(self): - return math.pi * self.radius ** 2 - -circle = Circle(5) -print(f"半径为{circle.radius}的圆,面积为{circle.calc_area():.2f}") -``` - -image-20260608202549418 - -B - -``` -### B组:巩固提升 - -#1. 定义 `Product` 类,包含名称、价格、库存三个属性。 -#2. 定义 `Book` 类,包含书名、作者、价格,添加 `show_info()` 方法。 -#3. 定义 `Student` 类,增加 `is_passed()` 方法判断是否及格。 -#4. 创建学生对象列表,计算全班平均分。 -class Product: - def __init__(self,name,price,stock): - self.name = name - self.price = price - self.stock = stock - - def show_into(self): - print(f"商品:{self.name},价格:{self.price}元,库存:{self.stock}件") - -product1 = Product("笔记本",3999,100) -product1.show_into() - -class Book: - def __init__(self,book_name,author,price,): - self.book_name = book_name - self.author = author - self.price = price - - def show_into(self): - print(f"书名:《{self.book_name}》,作者::{self.price},价格:{self.price}元") - -book = Book("Python入门到精通","张三",59.9) -book.show_into() - -class Student: - def __init__(self,name,score): - self.name = name - self.score = score - - def is_passed(self): - return self.score >= 60 - -students = [ - Student("小明",85), - Student("小红",58), - Student("小刚",92), - Student("小丽",77) -] - -for s in students: - print(f"{s.name} 分数:{s.score},是否及格:{'是' if s.is_passed() else '否'}") - -#计算平均分 -avg = sum(s.score for s in students)/len(students) -print(f"全班的平均分:{avg}") -``` - -image-20260608204225264 - -C - -``` -### C组:拓展挑战 - -#1. 完成课堂案例中的银行账户类。 -#2. 定义购物车类,支持添加商品和计算总价。 -#3. 定义课程类,保存课程名称、教师、学分。 -class BankAccount: - def __init__(self,name,balance=0): - self.name = name - self.balance =balance - - def deposit(self,money): - if money > 0: - self.balance += money - print(f"{self.name} 存入 {money}元,余额:{self.balance}元") - else: - print("存款金额必须大于0") - - def withdraw(self,money): - if 0 < money <= self.balance: - self.balance -= money - print(f"{self.name} 取出 {money} 元,余额 {self.balance} 元") - else: - print("取款金额不合法或余额不足!") - -account = BankAccount("张三",1000) -account.withdraw(300) -account.withdraw(500) - -class Cart: - def __init__(self): - self.items=[] - - def add_item(self,name,price): - self.items.append((name,price)) - print(f"已添加的商品:{name},单价:{price}元") - - def calc_total(self): - return sum(price for _,price in self.items) - -cart = Cart() -cart.add_item("牛奶",5) -cart.add_item("面包",8) -cart.add_item("鸡蛋",12) -print(f"购物车总价:{cart.calc_total()}元") - -class Course: - def __init__(self,course_name,teacher,credit): - self.course_name = course_name - self.teacher = teacher - self.credit = credit - - def show_info(self): - print(f"课程:{self.course_name},授课教师:{self.teacher},学分:{self.credit}") - -course = Course("Python程序设计","丘丘",4) -course.show_info() -``` - -image-20260608205701423 \ No newline at end of file diff --git "a/python-basics/38 \345\272\204\346\200\277/20260603 \346\226\207\344\273\266\346\223\215\344\275\234\344\275\234\344\270\232.md" "b/python-basics/38 \345\272\204\346\200\277/20260603 \346\226\207\344\273\266\346\223\215\344\275\234\344\275\234\344\270\232.md" deleted file mode 100644 index 5b3ff62..0000000 --- "a/python-basics/38 \345\272\204\346\200\277/20260603 \346\226\207\344\273\266\346\223\215\344\275\234\344\275\234\344\270\232.md" +++ /dev/null @@ -1,98 +0,0 @@ -A - -``` -### 基础练习(每个子场景都做一遍) - -#1. **文本文件**:创建 `mylog.txt`,写入三行“今天学习了文件操作”,再读出来打印。 -with open("mylog.txt", "w",encoding="utf-8") as f: - for _ in range(3): - f.write("今天学习了文件操作\n") - -with open ("mylog.txt", "r",encoding="utf-8") as f: - content = f.read() -print(content) -#2. **CSV**:自己建一个通讯录 CSV(姓名、电话),用代码添加一条新记录。 -import csv - -with open("contaxts.csv", "w",encoding="utf-8", newline="") as f: - writer = csv.writer(f) - writer.writerow(["姓名","电话"]) - -new_contact = ["张三","19091582870"] -with open("contaxts.csv", "a",encoding="utf",newline="") as f: - writer = csv.writer(f) - writer.writerow(new_contact) - -print("已添加联系人:",new_contact) -#3. **JSON**:把你自己的一首喜欢的诗保存为 JSON(包括标题、作者、正文)。 -import json - -poem = { - "标题":"静夜思", - "作者":"李白", - "正文":"床前明月光,疑是地上霜。举头望明月,低头思故乡。" -} - -with open("poem.json", "w",encoding="utf-8") as f: - json.dump(poem, f, ensure_ascii=False,indent=4) - -print("已保存《静夜思》到poem.json") -#4. **Excel**:用 pandas 读取上面生成的 CSV,保存为 Excel 文件。 -import pandas as pd - -df = pd.read_csv("contacts.csv",encoding="utf-8") -df.to_excel("contacts.xlsx",index=False) -print("已将 contacts.csv 转换为 contacts.xlsx") -``` - -image-20260608211812849 - -B - -``` -### 巩固练习(扩展项目功能) - -import csv -import json -import pandas as pd -import datetime -#1. 修改成绩转换程序,让日志也记录“本次处理了多少名学生”。 -students = [] -with open("score.csv","r",encoding="utf-8") as f: - reader = csv.DictReader(f) - for row in reader: - row["语文"] = int(row["语文"]) - row["数学"] = int(row["数学"]) - row["英语"] = int(row["英语"]) - students.append(row) - -count = len(students) -with open("mylog.txt","a",encoding="utf-8") as f: - f.write(f"{datetime.datetime.now()} 本次处理了 {count} 名学生\n") - -print(f"已处理 {count} 名学生,日志已写入 mylog.txt") -#2. 写一个函数,输入一个名字,读取对应的 JSON 文件,打印出该学生的所有成绩。 -def get_student_score(name): - try: - with open(f"{name}.json","r",encoding="utf") as f: - data = json.load(f) - print(f"\n{name}的成绩") - print(f"语文: {data['语文']},数学:{data['数学']},英语:{data['英语']}") - except FileNotFoundError: - print(f"未找到 {name} 的成绩文件") - -for stu in students: - with open(f"{stu['姓名']}.json","w",encoding="utf-8") as f: - json.dump(stu,f,ensure_ascii=False,indent=4) - -get_student_score("张三") -#3. 读取生成的 Excel 文件,筛选出平均分 ≥ 85 的学生,保存为 `优秀学生.xlsx`。 -df = pd.read_excel("contacts.xlsx") -df = pd.read_asv("scores.csv",encoding="utf-8") -df["平均分"] = df[["语文","数学","英语"]].mean(axis=1) - -excellent = df[df["平均分"] >= 85] -excellent.to_excel("优秀学生.xlsx",index=False) -print("已筛选平均分>=85分的学生,保存为 优秀学生.xlsx") -print(excellent[["姓名","平均分"]] -``` \ No newline at end of file diff --git a/python-basics/README.md b/python-basics/README.md deleted file mode 100644 index 74af5f1..0000000 --- a/python-basics/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Life’s pathetic, let’s pythonic. -——人生苦短,python是岸 - - -- Gitee