第15课:格式化输出魔法——f-string格式化

🎯 本课目标

  • 掌握f-string格式化输出的方法
  • 学会控制数字的显示格式
  • 掌握文本对齐和填充技巧
  • 制作美观的表格和报告
  • 在实际项目中应用格式化输出

✨ 趣味引入:数据的"化妆术"

想象一下:你的数据就像素颜的演员,需要化妆才能上台表演:

  • 🔢 数字:需要控制小数位数
  • 🔤 文字:需要对齐和美化
  • 📊 表格:需要整齐排列
  • 🎨 颜色:需要添加表情符号

今天,我们要学习的就是数据的"化妆术"——f-string格式化输出!让我们把普通的数据变成漂亮的展示!


🔧 第一部分:认识f-string

1.1 什么是f-string?

# f-string 基础
print("🎨 认识f-string")
print("=" * 30)

# 变量
name = "小明"
age = 12
score = 95.5
is_happy = True

# 传统方法
print("1. 传统方法:")
print("姓名:" + name + ",年龄:" + str(age) + ",成绩:" + str(score))
print()

# f-string方法(Python 3.6+)
print("2. f-string方法:")
print(f"姓名:{name},年龄:{age},成绩:{score}")
print(f"开心吗?{is_happy}")
print()

# 在字符串中直接计算
print("3. 在字符串中计算:")
print(f"明年年龄:{age + 1}")
print(f"成绩等级:{'优秀' if score >= 90 else '良好'}")

1.2 基本用法练习

# f-string基本用法练习
print("\n💡 f-string基本用法练习")
print("=" * 30)

# 学生信息
student = {
    "name": "张小红",
    "age": 11,
    "grade": "五年级",
    "chinese": 88.5,
    "math": 92.0,
    "english": 85.0
}

# 使用f-string格式化输出
info = f"""
📚 学生信息卡
{'='*30}
👤 姓名:{student['name']}
🎂 年龄:{student['age']}岁
🏫 年级:{student['grade']}
{'='*30}
📊 成绩单:
  语文:{student['chinese']}分
  数学:{student['math']}分
  英语:{student['english']}分
{'='*30}
📈 统计:
  总分:{student['chinese'] + student['math'] + student['english']}分
  平均分:{(student['chinese'] + student['math'] + student['english']) / 3:.1f}分
{'='*30}
"""

print(info)

🔢 第二部分:数字格式化

2.1 控制小数位数

# 数字格式化
print("🔢 数字格式化")
print("=" * 30)

# 各种数字
pi = 3.141592653589793
price = 99.99
percentage = 0.8567
big_number = 1234567.89

print("1. 控制小数位数:")
print(f"π的值:{pi}")  # 默认
print(f"π(两位小数):{pi:.2f}")
print(f"π(四位小数):{pi:.4f}")
print()

print("2. 价格显示:")
print(f"价格:{price:.2f}元")
print(f"价格(带千分位):{big_number:,.2f}元")
print()

print("3. 百分比显示:")
print(f"百分比:{percentage:.1%}")  # 85.7%
print(f"百分比(两位小数):{percentage:.2%}")  # 85.67%
print()

print("4. 科学计数法:")
print(f"科学计数:{big_number:.2e}")

2.2 数字对齐

# 数字对齐
print("\n📊 数字对齐")
print("=" * 30)

# 商品列表
products = [
    {"name": "笔记本", "price": 5.5, "quantity": 10},
    {"name": "钢笔", "price": 12.8, "quantity": 5},
    {"name": "橡皮", "price": 2.0, "quantity": 20},
    {"name": "尺子", "price": 3.5, "quantity": 15},
    {"name": "笔袋", "price": 25.0, "quantity": 3}
]

print("🛍️ 商品列表:")
print("-" * 40)
print(f"{'商品':<6} {'单价':>8} {'数量':>6} {'小计':>8}")
print("-" * 40)

total = 0
for product in products:
    subtotal = product["price"] * product["quantity"]
    total += subtotal
    
    # 使用f-string对齐
    print(f"{product['name']:<6} {product['price']:>8.2f}元 "
          f"{product['quantity']:>6}件 {subtotal:>8.2f}元")

print("-" * 40)
print(f"{'总计:':<22} {total:>8.2f}元")

🔤 第三部分:文本格式化

3.1 文本对齐

# 文本对齐
print("🔤 文本对齐")
print("=" * 30)

# 对齐方式
text = "Python"
width = 20

print("1. 左对齐:")
print(f"|{text:<{width}}|")
print(f"|{'小明':<{width}}|")
print(f"|{'编程学习':<{width}}|")
print()

print("2. 右对齐:")
print(f"|{text:>{width}}|")
print(f"|{'小明':>{width}}|")
print(f"|{'编程学习':>{width}}|")
print()

print("3. 居中对齐:")
print(f"|{text:^{width}}|")
print(f"|{'小明':^{width}}|")
print(f"|{'编程学习':^{width}}|")

3.2 填充字符

# 填充字符
print("\n🎨 填充字符")
print("=" * 30)

# 使用不同字符填充
name = "小明"
score = 95

print("1. 用空格填充:")
print(f"|{name:10}|{score:5}|")
print()

print("2. 用点填充:")
print(f"|{name:.<10}|{score:.>5}|")
print()

print("3. 用等号填充:")
print(f"|{name:=^20}|")
print(f"|{'成绩单':=^20}|")
print()

print("4. 用星号填充:")
header = " 学生信息 "
print(f"{header:*^30}")
print(f"*{'姓名:小明':^28}*")
print(f"*{'年龄:12岁':^28}*")
print(f"*{'成绩:95分':^28}*")
print("*" * 30)

3.3 实际应用:课程表

# 课程表格式化
print("\n📅 精美课程表")
print("=" * 40)

# 课程表数据
schedule = [
    ["时间", "星期一", "星期二", "星期三", "星期四", "星期五"],
    ["08:00-08:40", "语文", "数学", "英语", "语文", "数学"],
    ["08:50-09:30", "数学", "语文", "数学", "英语", "语文"],
    ["10:00-10:40", "英语", "科学", "体育", "数学", "英语"],
    ["10:50-11:30", "美术", "英语", "语文", "科学", "体育"],
    ["14:00-14:40", "体育", "美术", "音乐", "班会", "美术"]
]

# 定义列宽
col_width = 12

# 打印课程表
print("╔" + "═" * (col_width * 6 - 1) + "╗")
for i, row in enumerate(schedule):
    if i == 0:  # 表头
        row_str = "║" + "║".join(f"{cell:^{col_width}}" for cell in row) + "║"
    else:  # 数据行
        row_str = "║" + "║".join(f"{cell:^{col_width}}" for cell in row) + "║"
    
    print(row_str)
    
    # 分隔线
    if i == 0:
        print("╠" + "═" * (col_width * 6 - 1) + "╣")
    elif i < len(schedule) - 1:
        print("╟" + "─" * (col_width * 6 - 1) + "╢")

print("╚" + "═" * (col_width * 6 - 1) + "╝")

🎨 第四部分:综合格式化应用

4.1 成绩报告单

# 成绩报告单
print("📊 精美成绩报告单")
print("=" * 50)

# 学生数据
students = [
    {"name": "张小明", "chinese": 88.5, "math": 92.0, "english": 85.0, "science": 90.5},
    {"name": "李小红", "chinese": 92.5, "math": 88.0, "english": 91.5, "science": 87.0},
    {"name": "王刚", "chinese": 85.0, "math": 95.5, "english": 82.0, "science": 93.5},
    {"name": "刘芳", "chinese": 90.0, "math": 89.5, "english": 88.0, "science": 91.0},
    {"name": "陈伟", "chinese": 78.5, "math": 85.0, "english": 79.5, "science": 82.0}
]

# 表头
header = "🌟 五年级期末成绩报告 🌟"
print(f"{header:^50}")
print("=" * 50)
print()

# 列标题
print(f"{'姓名':<6} {'语文':>6} {'数学':>6} {'英语':>6} {'科学':>6} {'总分':>7} {'平均分':>7} {'等级':>6}")
print("-" * 50)

# 打印每个学生的成绩
for student in students:
    # 计算
    total = student["chinese"] + student["math"] + student["english"] + student["science"]
    average = total / 4
    
    # 判断等级
    if average >= 90:
        grade = "A"
        grade_symbol = "⭐"
    elif average >= 80:
        grade = "B"
        grade_symbol = "👍"
    elif average >= 70:
        grade = "C"
        grade_symbol = "💪"
    else:
        grade = "D"
        grade_symbol = "📈"
    
    # 格式化输出
    print(f"{student['name']:<6} "
          f"{student['chinese']:>6.1f} "
          f"{student['math']:>6.1f} "
          f"{student['english']:>6.1f} "
          f"{student['science']:>6.1f} "
          f"{total:>7.1f} "
          f"{average:>7.1f} "
          f"{grade_symbol} {grade:>4}")

print("-" * 50)

# 班级统计
class_avg_chinese = sum(s["chinese"] for s in students) / len(students)
class_avg_math = sum(s["math"] for s in students) / len(students)
class_avg_english = sum(s["english"] for s in students) / len(students)
class_avg_science = sum(s["science"] for s in students) / len(students)
class_total_avg = (class_avg_chinese + class_avg_math + class_avg_english + class_avg_science) / 4

print(f"\n📈 班级平均分:")
print(f"  语文:{class_avg_chinese:6.1f}分")
print(f"  数学:{class_avg_math:6.1f}分")
print(f"  英语:{class_avg_english:6.1f}分")
print(f"  科学:{class_avg_science:6.1f}分")
print(f"  总平均:{class_total_avg:6.1f}分")

4.2 图书管理系统界面

# 图书管理系统界面
print("📚 小小图书馆管理系统")
print("=" * 60)

# 图书数据
books = [
    {"id": "B001", "title": "Python编程入门", "author": "张老师", "price": 45.5, "quantity": 5},
    {"id": "B002", "title": "数学趣味故事", "author": "李教授", "price": 32.8, "quantity": 3},
    {"id": "B003", "title": "科学探索之旅", "author": "王博士", "price": 58.0, "quantity": 7},
    {"id": "B004", "title": "中华上下五千年", "author": "历史编委会", "price": 68.5, "quantity": 4},
    {"id": "B005", "title": "英语故事集", "author": "外语出版社", "price": 29.9, "quantity": 6}
]

# 系统标题
title = "📖 图书目录"
print(f"\n{title:^60}")
print("═" * 60)

# 表头
print(f"{'编号':<8} {'书名':<20} {'作者':<12} {'价格':>8} {'库存':>6} {'状态':>6}")
print("─" * 60)

# 图书列表
for book in books:
    # 判断状态
    status = "充足" if book["quantity"] >= 5 else "紧张" if book["quantity"] >= 1 else "缺货"
    status_symbol = "✅" if book["quantity"] >= 5 else "⚠️" if book["quantity"] >= 1 else "❌"
    
    print(f"{book['id']:<8} "
          f"{book['title']:<20} "
          f"{book['author']:<12} "
          f"{book['price']:>8.1f}元 "
          f"{book['quantity']:>6}本 "
          f"{status_symbol} {status:>5}")

print("═" * 60)

# 统计信息
total_books = sum(book["quantity"] for book in books)
total_value = sum(book["price"] * book["quantity"] for book in books)
available_books = len([b for b in books if b["quantity"] > 0])

print(f"\n📊 统计信息:")
print(f"  📖 图书总数:{total_books}本")
print(f"  💰 总价值:{total_value:.1f}元")
print(f"  📋 图书种类:{len(books)}种")
print(f"  ✅ 有库存:{available_books}种")

🎮 第五部分:格式化游戏

游戏1:格式化挑战

# 格式化挑战
print("🎯 格式化输出挑战")
print("=" * 30)

# 挑战题目
challenges = [
    {
        "description": "将数字3.14159格式化为两位小数",
        "code": "pi = 3.14159",
        "format_spec": ".2f",
        "answer": "3.14"
    },
    {
        "description": "将'Python'居中对齐,宽度20,用'*'填充",
        "code": "text = 'Python'",
        "format_spec": "*^20",
        "answer": "*******Python*******"
    },
    {
        "description": "将数字1234.567格式化为带千分位,两位小数",
        "code": "num = 1234.567",
        "format_spec": ",.2f",
        "answer": "1,234.57"
    },
    {
        "description": "将0.8567格式化为百分比,一位小数",
        "code": "p = 0.8567",
        "format_spec": ".1%",
        "answer": "85.7%"
    },
    {
        "description": "将'小明'左对齐,宽度10,用'.'填充",
        "code": "name = '小明'",
        "format_spec": ".<10",
        "answer": "小明........"
    }
]

score = 0
print("请写出正确的格式化代码:")
print("格式:f'{变量:{格式说明符}}'")
print()

for i, challenge in enumerate(challenges, 1):
    print(f"{i}. {challenge['description']}")
    print(f"   代码:{challenge['code']}")
    
    user_input = input("   格式化代码:").strip()
    
    # 执行代码验证
    try:
        # 执行原始代码
        exec(challenge['code'])
        
        # 获取变量名
        var_name = challenge['code'].split('=')[0].strip()
        
        # 尝试执行用户输入的格式化
        test_code = f"result = f'{{{var_name}:{user_input}}}'"
        exec(test_code)
        result = locals().get('result', '')
        
        if result == challenge['answer']:
            print("   ✅ 正确!")
            score += 1
        else:
            print(f"   ❌ 错误!正确答案是:{{{var_name}:{challenge['format_spec']}}}")
            print(f"      结果:{challenge['answer']}")
    except:
        print(f"   ❌ 格式错误!正确答案是:{{{var_name}:{challenge['format_spec']}}}")
    
    print()

print(f"📊 得分:{score}/{len(challenges)}")
if score == len(challenges):
    print("🎉 格式化大师!")
elif score >= 3:
    print("👍 很棒!继续努力!")
else:
    print("💪 加油!多加练习!")

游戏2:制作生日贺卡

# 生日贺卡制作器
print("🎂 生日贺卡制作器")
print("=" * 40)

# 输入信息
name = input("寿星姓名:")
age = int(input("寿星年龄:"))
sender = input("你的姓名:")
message = input("祝福语:")

# 生成贺卡
card_width = 50

print("\n" + "🎁" * 25)
print()

# 贺卡标题
title = f"🎂 生日贺卡 🎂"
print(title.center(card_width))

# 装饰线
print("✨" * card_width)

# 寿星信息
print(f"\n{'亲爱的:':>{card_width//2}}")
print(f"{name:^{card_width}}")
print(f"{'🎉 生日快乐!🎉':^{card_width}}")
print(f"{f'祝你 {age} 岁生日快乐!':^{card_width}}")

# 祝福语
print(f"\n{'🎀 祝福语 🎀':^{card_width}}")
print("-" * card_width)

# 处理长祝福语
words = message.split()
lines = []
current_line = ""
for word in words:
    if len(current_line) + len(word) + 1 <= card_width - 4:
        current_line += word + " "
    else:
        lines.append(current_line.strip())
        current_line = word + " "
if current_line:
    lines.append(current_line.strip())

for line in lines:
    print(f"  {line:^{card_width-4}}")

print("-" * card_width)

# 落款
print(f"\n{'来自:':>{card_width-20}}")
print(f"{sender:>{card_width-10}}")
print(f"{'❤️':>{card_width-5}}")

# 装饰线
print("\n" + "🎁" * 25)
print()

# 保存贺卡选项
save = input("是否保存贺卡到文件?(是/否): ")
if save.lower() in ['是', 'yes', 'y']:
    filename = f"{name}_生日贺卡.txt"
    with open(filename, 'w', encoding='utf-8') as f:
        f.write("🎁" * 25 + "\n\n")
        f.write(title.center(card_width) + "\n")
        f.write("✨" * card_width + "\n\n")
        f.write(f"{'亲爱的:':>{card_width//2}}\n")
        f.write(f"{name:^{card_width}}\n")
        f.write(f"{'🎉 生日快乐!🎉':^{card_width}}\n")
        f.write(f"{f'祝你 {age} 岁生日快乐!':^{card_width}}\n\n")
        f.write(f"{'🎀 祝福语 🎀':^{card_width}}\n")
        f.write("-" * card_width + "\n")
        for line in lines:
            f.write(f"  {line:^{card_width-4}}\n")
        f.write("-" * card_width + "\n\n")
        f.write(f"{'来自:':>{card_width-20}}\n")
        f.write(f"{sender:>{card_width-10}}\n")
        f.write(f"{'❤️':>{card_width-5}}\n\n")
        f.write("🎁" * 25)
    
    print(f"✅ 贺卡已保存到:{filename}")

📁 第六部分:实际项目应用

项目1:学生信息管理系统界面

# 学生信息管理系统界面
print("🎒 学生信息管理系统")
print("=" * 60)

# 模拟数据
students = [
    {"id": "S001", "name": "张小明", "age": 12, "grade": "五年级", "phone": "13800138001"},
    {"id": "S002", "name": "李小红", "age": 11, "grade": "四年级", "phone": "13800138002"},
    {"id": "S003", "name": "王刚", "age": 12, "grade": "五年级", "phone": "13800138003"},
    {"id": "S004", "name": "刘芳", "age": 11, "grade": "四年级", "phone": "13800138004"},
    {"id": "S005", "name": "陈伟", "age": 12, "grade": "五年级", "phone": "13800138005"}
]

while True:
    print("\n" + "═" * 60)
    print("请选择功能:")
    print("═" * 60)
    print("1. 📋 查看所有学生")
    print("2. 🔍 搜索学生")
    print("3. ➕ 添加学生")
    print("4. ✏️ 编辑学生")
    print("5. 🗑️ 删除学生")
    print("6. 💾 导出数据")
    print("7. 🚪 退出系统")
    print("═" * 60)
    
    choice = input("\n请输入选择 (1-7): ")
    
    if choice == "1":
        # 查看所有学生
        print("\n" + "=" * 60)
        print(f"{'📋 学生列表':^60}")
        print("=" * 60)
        print(f"{'学号':<8} {'姓名':<8} {'年龄':<6} {'年级':<8} {'电话':<15}")
        print("-" * 60)
        
        for student in students:
            print(f"{student['id']:<8} "
                  f"{student['name']:<8} "
                  f"{student['age']:<6}岁 "
                  f"{student['grade']:<8} "
                  f"{student['phone']:<15}")
        
        print("=" * 60)
        
    elif choice == "2":
        # 搜索学生
        keyword = input("\n请输入搜索关键词(姓名或学号): ")
        print("\n" + "-" * 60)
        print(f"{'🔍 搜索结果':^60}")
        print("-" * 60)
        
        found = False
        for student in students:
            if keyword in student['name'] or keyword in student['id']:
                if not found:
                    print(f"{'学号':<8} {'姓名':<8} {'年龄':<6} {'年级':<8} {'电话':<15}")
                    print("-" * 60)
                    found = True
                
                print(f"{student['id']:<8} "
                      f"{student['name']:<8} "
                      f"{student['age']:<6}岁 "
                      f"{student['grade']:<8} "
                      f"{student['phone']:<15}")
        
        if not found:
            print(f"{'没有找到匹配的学生':^60}")
        print("-" * 60)
        
    elif choice == "3":
        # 添加学生
        print("\n" + "+" * 60)
        print(f"{'➕ 添加新学生':^60}")
        print("+" * 60)
        
        new_id = f"S{len(students)+1:03d}"
        name = input("姓名: ")
        age = int(input("年龄: "))
        grade = input("年级: ")
        phone = input("电话: ")
        
        students.append({
            "id": new_id,
            "name": name,
            "age": age,
            "grade": grade,
            "phone": phone
        })
        
        print(f"\n✅ 学生 {name} 添加成功!学号: {new_id}")
        
    elif choice == "7":
        # 退出系统
        print("\n" + "🎉" * 30)
        print(f"{'感谢使用学生信息管理系统':^60}")
        print(f"{'再见!👋':^60}")
        print("🎉" * 30)
        break
        
    else:
        print("\n❌ 功能开发中,敬请期待!")
    
    input("\n按回车键继续...")

项目2:个人记账本

# 个人记账本
print("💰 个人记账本")
print("=" * 50)

# 账本数据
records = []
balance = 1000.0  # 初始余额

while True:
    # 显示当前余额
    print("\n" + "═" * 50)
    print(f"{'💰 当前余额':^25} : {balance:>10.2f}元")
    print("═" * 50)
    
    print("\n请选择操作:")
    print("1. 📝 记录收入")
    print("2. 💸 记录支出")
    print("3. 📊 查看明细")
    print("4. 📈 统计图表")
    print("5. 💾 导出报表")
    print("6. 🚪 退出")
    
    choice = input("\n请选择 (1-6): ")
    
    if choice == "1":
        # 记录收入
        print("\n" + "+" * 50)
        print(f"{'📝 记录收入':^50}")
        print("+" * 50)
        
        amount = float(input("收入金额: "))
        category = input("收入类别 (如: 零花钱/礼物/其他): ")
        description = input("收入说明: ")
        
        balance += amount
        records.append({
            "type": "收入",
            "amount": amount,
            "category": category,
            "description": description,
            "balance": balance
        })
        
        print(f"\n✅ 收入记录成功! +{amount:.2f}元")
        
    elif choice == "2":
        # 记录支出
        print("\n" + "-" * 50)
        print(f"{'💸 记录支出':^50}")
        print("-" * 50)
        
        amount = float(input("支出金额: "))
        
        if amount > balance:
            print("❌ 余额不足!")
            continue
            
        category = input("支出类别 (如: 食物/学习/娱乐): ")
        description = input("支出说明: ")
        
        balance -= amount
        records.append({
            "type": "支出",
            "amount": amount,
            "category": category,
            "description": description,
            "balance": balance
        })
        
        print(f"\n✅ 支出记录成功! -{amount:.2f}元")
        
    elif choice == "3":
        # 查看明细
        if not records:
            print("\n📭 还没有任何记录")
            continue
            
        print("\n" + "=" * 80)
        print(f"{'📊 收支明细':^80}")
        print("=" * 80)
        print(f"{'类型':<6} {'金额':>10} {'类别':<8} {'说明':<20} {'余额':>15} {'时间':<10}")
        print("-" * 80)
        
        # 显示最近的10条记录
        for i, record in enumerate(records[-10:], 1):
            # 使用不同颜色符号
            type_symbol = "💰" if record["type"] == "收入" else "💸"
            
            print(f"{type_symbol} {record['type']:<4} "
                  f"{record['amount']:>10.2f}元 "
                  f"{record['category']:<8} "
                  f"{record['description']:<20} "
                  f"{record['balance']:>15.2f}元 "
                  f"{i:>4}")
        
        print("=" * 80)
        
        # 统计
        total_income = sum(r["amount"] for r in records if r["type"] == "收入")
        total_expense = sum(r["amount"] for r in records if r["type"] == "支出")
        
        print(f"\n📈 统计: ")
        print(f"  总收入: {total_income:>10.2f}元")
        print(f"  总支出: {total_expense:>10.2f}元")
        print(f"  净收入: {(total_income - total_expense):>10.2f}元")
        
    elif choice == "6":
        # 退出
        print("\n" + "🎉" * 25)
        print(f"{'感谢使用个人记账本':^50}")
        print(f"{'祝您生活愉快!💰':^50}")
        print("🎉" * 25)
        break
        
    else:
        print("\n❌ 功能开发中,敬请期待!")

📅 下节课预告

第16课:注释小助手——养成好习惯

下节课你将学习:

  1. 单行注释和多行注释的写法
  2. 为什么需要写注释
  3. 如何写出好的注释
  4. 文档字符串的使用
  5. 养成编程好习惯

预习思考

  1. 注释是什么?为什么要写注释?
  2. 什么样的注释是有用的?
  3. 如何让代码更容易理解?

💬 给家长的话

亲爱的家长

今天孩子学习了f-string格式化输出,这是Python中非常强大和实用的功能,能让程序的输出更加美观和专业。

孩子今天学会了

  1. ✅ 使用f-string进行格式化输出
  2. ✅ 控制数字的显示格式
  3. ✅ 对齐和填充文本
  4. ✅ 制作美观的表格和报告
  5. ✅ 在实际项目中应用格式化

格式化输出的重要性

| 格式化技巧 | 应用场景 | 实际意义 | 能力培养 |

|----------|---------|---------|---------|

| 数字格式 | 价格、成绩、百分比 | 精确显示 | 数据呈现 |

| 文本对齐 | 表格、列表、标题 | 美观整齐 | 视觉设计 |

| 填充字符 | 边框、分隔线 | 增强可读性 | 界面设计 |

| 综合应用 | 报告、卡片、界面 | 专业输出 | 综合能力 |

您可以这样做

生活应用

  1. 家庭记账:用格式化输出制作漂亮的账本
  2. 成绩管理:制作美观的成绩报告单
  3. 节日贺卡:用Python制作电子贺卡
  4. 学习计划:制作整齐的学习计划表

思维训练

  1. 讨论:什么样的输出是美观的?
  2. 思考:如何设计清晰的数据展示?
  3. 设计:创建自己的数据报表模板
  4. 实践:用格式化技巧美化之前的程序

温馨提示

  • 格式化输出让程序更专业
  • 美观的界面提升用户体验
  • 鼓励孩子在输出上下功夫
  • 通过实际项目练习格式化技巧

🏆 今日成就

完成了今天的学习,你:

掌握了f-string格式化

🔢 学会了数字格式化

🔤 掌握了文本对齐

📊 能制作漂亮表格

🎨 提升了输出美观度

挑战任务

  1. 为家庭制作月度收支报表
  2. 设计个人成绩管理系统界面
  3. 创建电子生日贺卡生成器
  4. 制作课程表美化工具

🌟 编程心法

输出是程序的面孔
格式化是美丽的妆容
数字要精确
文字要对齐
表格要整齐
报告要清晰
用f-string施展魔法
让数据穿上华服
让输出闪耀光芒
从今天起
让你的程序更加美丽

记住:良好的格式化能力,让你的程序输出更专业、更美观。这是成为优秀程序员的重要素养!


第15课结束。你现在已经掌握了格式化输出的魔法!

实践任务:

1. 制作家庭财务报表

2. 设计成绩管理系统界面

3. 创建电子贺卡制作器

4. 美化之前的程序输出

下节课,让我们学习写注释,养成编程好习惯!

第16课见!📝