Python 输入与输出

0 阅读6分钟

Python 输入与输出

目录


输出函数 print()

基本用法

print() 是 Python 中最常用的输出函数,用于将内容显示在控制台。

# 输出字符串
print("Hello, World!")

# 输出数字
print(42)

# 输出变量
name = "张三"
print(name)

多个参数输出

# 默认用空格分隔
print("姓名:", "张三", "年龄:", 25)
# 输出: 姓名: 张三 年龄: 25

# 自定义分隔符
print("2024", "01", "15", sep="-")
# 输出: 2024-01-15

print("apple", "banana", "orange", sep=", ")
# 输出: apple, banana, orange

end 参数

默认情况下,print() 会在末尾添加换行符 \n。可以使用 end 参数修改。

# 不换行输出
print("Hello", end=" ")
print("World")
# 输出: Hello World

# 自定义结尾
print("第一行", end=" | ")
print("第二行", end=" | ")
print("第三行")
# 输出: 第一行 | 第二行 | 第三行

file 参数

可以将输出重定向到文件或其他流。

# 输出到文件
with open("output.txt", "w") as f:
    print("这是写入文件的内容", file=f)

输入函数 input()

基本用法

input() 函数用于从用户获取输入,返回值为字符串类型。

# 获取用户输入
name = input("请输入您的姓名: ")
print(f"您好, {name}!")

# 注意:input() 返回的永远是字符串
age = input("请输入您的年龄: ")
print(type(age))  # <class 'str'>

类型转换

由于 input() 返回的是字符串,需要根据实际需求进行类型转换。

# 转换为整数
age = int(input("请输入年龄: "))
print(f"明年您将是 {age + 1} 岁")

# 转换为浮点数
height = float(input("请输入身高(米): "))
print(f"您的身高是 {height} 米")

# 转换为布尔值(需要特殊处理)
answer = input("是否继续? (yes/no): ")
is_continue = answer.lower() == "yes"

输入验证

# 安全的数字输入
while True:
    try:
        age = int(input("请输入年龄: "))
        if 0 < age < 150:
            break
        else:
            print("请输入有效的年龄!")
    except ValueError:
        print("请输入一个整数!")

print(f"您的年龄是: {age}")

格式化输出

f-string(推荐,Python 3.6+)

f-string 是最现代、最简洁的格式化方式。

name = "李四"
age = 30
height = 1.75

# 基本用法
print(f"姓名: {name}, 年龄: {age}")

# 表达式计算
print(f"明年年龄: {age + 1}")

# 格式化数字
print(f"身高: {height:.2f} 米")  # 保留两位小数
print(f"百分比: {0.856:.1%}")     # 85.6%

# 对齐和填充
print(f"{'左对齐':<10}|{'右对齐':>10}|{'居中':^10}|")
# 输出: 左对齐      |      右对齐|   居中    |

# 宽度填充
number = 42
print(f"编号: {number:05d}")  # 输出: 编号: 00042

format() 方法

name = "王五"
age = 25

# 位置参数
print("姓名: {}, 年龄: {}".format(name, age))

# 索引参数
print("姓名: {0}, 年龄: {1}, 姓名: {0}".format(name, age))

# 关键字参数
print("姓名: {n}, 年龄: {a}".format(n=name, a=age))

# 格式化数字
pi = 3.1415926
print("π ≈ {:.2f}".format(pi))  # 输出: π ≈ 3.14
print("π ≈ {:.4f}".format(pi))  # 输出: π ≈ 3.1416

% 格式化(旧式,不推荐)

name = "赵六"
age = 28

# 字符串格式化
print("姓名: %s, 年龄: %d" % (name, age))

# 浮点数格式化
price = 99.9
print("价格: %.2f 元" % price)

对比总结

方式优点缺点
f-string简洁、高效、可读性好仅 Python 3.6+
format()灵活、兼容性好语法较繁琐
% 格式化熟悉 C 语言者易上手功能有限、不推荐

推荐使用 f-string!


文件读写

写入文件

# 方式1: 使用 with 语句(推荐)
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("第一行内容\n")
    f.write("第二行内容\n")

# 方式2: 使用 print
with open("test.txt", "w", encoding="utf-8") as f:
    print("这是第一行", file=f)
    print("这是第二行", file=f)

读取文件

# 读取全部内容
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# 逐行读取
with open("test.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # strip() 去除换行符

# 读取所有行为列表
with open("test.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    print(lines)

追加模式

# 追加内容到文件末尾
with open("test.txt", "a", encoding="utf-8") as f:
    f.write("这是追加的内容\n")

文件打开模式

模式说明
r只读(默认)
w写入(覆盖原内容)
a追加
r+读写
w+读写(覆盖原内容)
a+读写(追加)

实战练习

练习1: 个人信息收集器

print("=" * 40)
print("   欢迎使用个人信息收集器")
print("=" * 40)

name = input("请输入姓名: ")
age = int(input("请输入年龄: "))
city = input("请输入城市: ")
hobby = input("请输入爱好: ")

print("\n" + "=" * 40)
print("   您的个人信息")
print("=" * 40)
print(f"姓名: {name}")
print(f"年龄: {age}")
print(f"城市: {city}")
print(f"爱好: {hobby}")
print("=" * 40)

练习2: 简易计算器

print("=== 简易计算器 ===")

num1 = float(input("请输入第一个数字: "))
operator = input("请输入运算符 (+, -, *, /): ")
num2 = float(input("请输入第二个数字: "))

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        result = "错误: 除数不能为零!"
else:
    result = "错误: 无效的运算符!"

print(f"\n结果: {num1} {operator} {num2} = {result}")

练习3: 学生成绩管理系统

students = []

while True:
    print("\n=== 学生成绩管理系统 ===")
    print("1. 添加学生")
    print("2. 查看所有学生")
    print("3. 退出")

    choice = input("请选择操作 (1/2/3): ")

    if choice == "1":
        name = input("请输入学生姓名: ")
        score = float(input("请输入成绩: "))
        students.append({"name": name, "score": score})
        print(f"学生 {name} 添加成功!")

    elif choice == "2":
        if not students:
            print("暂无学生数据")
        else:
            print(f"\n{'姓名':<10} {'成绩':<10} {'等级':<10}")
            print("-" * 30)
            for student in students:
                score = student["score"]
                if score >= 90:
                    grade = "优秀"
                elif score >= 80:
                    grade = "良好"
                elif score >= 60:
                    grade = "及格"
                else:
                    grade = "不及格"
                print(f"{student['name']:<10} {score:<10.1f} {grade:<10}")

    elif choice == "3":
        print("感谢使用,再见!")
        break
    else:
        print("无效选择,请重新输入")

练习4: 日记本程序

import datetime

def write_diary():
    """写日记"""
    today = datetime.datetime.now().strftime("%Y-%m-%d")
    filename = f"diary_{today}.txt"

    print(f"\n今天是 {today}")
    print("请输入今天的日记内容 (输入 'END' 结束):")

    lines = []
    while True:
        line = input()
        if line.upper() == "END":
            break
        lines.append(line)

    content = "\n".join(lines)

    with open(filename, "a", encoding="utf-8") as f:
        f.write(f"\n时间: {datetime.datetime.now().strftime('%H:%M:%S')}\n")
        f.write(content + "\n")
        f.write("-" * 40 + "\n")

    print("日记已保存!")

def read_diary():
    """读日记"""
    date = input("请输入日期 (YYYY-MM-DD): ")
    filename = f"diary_{date}.txt"

    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
            print(f"\n{date} 的日记:")
            print("=" * 40)
            print(content)
    except FileNotFoundError:
        print("该日期没有日记记录")

while True:
    print("\n=== 电子日记本 ===")
    print("1. 写日记")
    print("2. 读日记")
    print("3. 退出")

    choice = input("请选择: ")

    if choice == "1":
        write_diary()
    elif choice == "2":
        read_diary()
    elif choice == "3":
        print("再见!")
        break
    else:
        print("无效选择")

常见错误与注意事项

1. input() 返回值类型

# ❌ 错误示例
age = input("请输入年龄: ")
print(age + 1)  # TypeError: can only concatenate str to str

# ✅ 正确做法
age = int(input("请输入年龄: "))
print(age + 1)

2. 文件编码问题

# ❌ 可能导致中文乱码
with open("test.txt", "w") as f:
    f.write("中文内容")

# ✅ 指定编码
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("中文内容")

3. 忘记关闭文件

# ❌ 不推荐
f = open("test.txt", "r")
content = f.read()
# 如果中间出错,文件可能不会关闭

# ✅ 推荐:使用 with 语句自动管理
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
# 离开 with 块后自动关闭文件

4. 格式化字符串引号嵌套

name = "张三"

# ❌ 错误:引号冲突
# print(f"他说:"你好,{name}"")

# ✅ 正确:使用不同引号
print(f'他说:"你好,{name}"')
print(f"他说:'你好,{name}'")

小结

  • 输出: 使用 print() 函数,支持多种格式化方式
  • 输入: 使用 input() 函数,返回值始终是字符串
  • 格式化: 优先使用 f-string,简洁高效
  • 文件操作: 使用 with 语句自动管理文件资源
  • 类型转换: 注意 input() 返回值的类型转换

掌握输入输出是 Python 编程的基础,多练习才能熟练掌握!