def print_basic_output():
"""演示基本的输出方法"""
print("\n=== 基本输出 ===")
# 输出字符串
print("Hello, World!")
# 输出数字
print(100)
# 输出多个内容
print("Hello", "World", "Python")
def print_formatted_output():
"""演示格式化输出方法"""
print("\n=== 格式化输出 ===")
# 使用f-string(推荐)
name = "小明"
age = 18
print(f"我叫{name},今年{age}岁")
# 使用format方法
print("我叫{},今年{}岁".format(name, age))
# 使用%格式化(旧式方法)
print("我叫%s,今年%d岁" % (name, age))
def print_format_control():
"""演示输出格式控制"""
print("\n=== 格式控制 ===")
# 不换行输出
print("hello", end=" ")
print("world")
# 指定分隔符
print("hello", "world", "sd", sep="*")
# 指定结束符
print("hello", "world", "sd", end="!\n")
def print_file_operations():
"""演示文件操作"""
print("\n=== 文件操作 ===")
# 写入文件
with open("test.txt", "w") as file:
file.write("Hello, World!")
# 读取文件
with open("test.txt", "r") as file:
print(file.read())
def print_list_operations():
"""演示列表操作"""
print("\n=== 列表操作 ===")
# 创建列表
nums = [1, 2, 3, 4, 5]
print(f"原始列表: {nums}")
# 添加元素
nums.append(6)
print(f"添加元素后: {nums}")
# 插入元素
nums.insert(0, 0)
print(f"插入元素后: {nums}")
# 删除最后一个元素
nums.pop()
print(f"删除最后一个元素后: {nums}")
# 删除指定元素
nums.remove(3)
print(f"删除元素3后: {nums}")
def print_dict_operations():
"""演示字典操作"""
print("\n=== 字典操作 ===")
# 创建字典
person = {"name": "小明", "age": 18, "city": "北京"}
print(f"原始字典: {person}")
# 添加新键值对
person["gender"] = "男"
print(f"添加性别后: {person}")
def get_user_input():
"""获取用户输入"""
print("\n=== 用户输入 ===")
# 获取用户输入
name = input("请输入你的名字:")
print(f"你好,{name}!")
def main():
"""主函数"""
try:
# 调用各个功能函数
print_basic_output()
print_formatted_output()
print_format_control()
print_file_operations()
print_list_operations()
print_dict_operations()
get_user_input()
# 输出计算结果
print("\n=== 计算结果 ===")
print(f"1024*768={1024*768}")
print(f"100+200={100+200}")
except Exception as e:
print(f"发生错误: {e}")
finally:
print("\n=== 程序执行完毕 ===")
# 当作为主程序运行时执行
if __name__ == "__main__":
main()
输出结果:
=== 基本输出 ===
Hello, World!
100
Hello World Python
=== 格式化输出 ===
我叫小明,今年18岁
我叫小明,今年18岁
我叫小明,今年18岁
=== 格式控制 ===
hello world
hello*world*sd
hello world sd!
=== 文件操作 ===
Hello, World!
=== 列表操作 ===
原始列表: [1, 2, 3, 4, 5]
添加元素后: [1, 2, 3, 4, 5, 6]
插入元素后: [0, 1, 2, 3, 4, 5, 6]
删除最后一个元素后: [0, 1, 2, 3, 4, 5]
删除元素3后: [0, 1, 2, 4, 5]
=== 字典操作 ===
原始字典: {'name': '小明', 'age': 18, 'city': '北京'}
添加性别后: {'name': '小明', 'age': 18, 'city': '北京', 'gender': '男'}
=== 用户输入 ===
请输入你的名字:zhumeng
你好,zhumeng!
=== 计算结果 ===
1024*768=786432
100+200=300
=== 程序执行完毕 ===
使用建议:
- 优先使用f-string(Python 3.6+)
- 需要格式化时使用format()方法
- 简单输出直接用逗号分隔
- 需要控制格式时使用end和sep参数
- 输出到文件时使用file参数
注意事项:
- print()默认会换行
- 多个参数默认用空格分隔
- f-string中可以使用表达式
- 格式化字符串要使用正确的占位符