Python3 输入和输出:程序不是哑巴,它会说也会听
我是陈默,一个正拼命上岸的码农。
程序如果不会说话,你怎么知道它干了什么?
程序如果不会听话,你怎么告诉它要干什么?
输入和输出,是程序和外界沟通的唯一方式。一个从外面拿数据进来,一个把结果送出去。
今天我们把 Python 的输入输出彻底搞清楚。
1. 输出:print() 的全部本事
print() 是你最早学会的函数,但它的本事你可能只用了三成。
基本用法
print("你好") # 输出: 你好print(1 + 1) # 输出: 2print("我", "是", "陈默") # 输出: 我 是 陈默
自定义分隔符:sep
默认用空格分隔。你可以改:
print("2026", "04", "01", sep="-") # 输出: 2026-04-01print("苹果", "香蕉", "橙子", sep="、") # 输出: 苹果、香蕉、橙子print("A", "B", "C", sep="") # 输出: ABC
自定义结尾:end
默认每行结尾是换行 \n。你可以改:
# 不换行,用逗号分隔for i in range(5): print(i, end=", ")# 输出: 0, 1, 2, 3, 4,# 不换行,用空格print("加载中", end="")print("...完成")# 输出: 加载中...完成
输出到文件
with open("log.txt", "w") as f: print("这条信息写到文件里", file=f)
file 参数让 print 直接写入文件,不用 f.write()。
2. 格式化输出:把变量塞进字符串
f-string:最推荐
Python 3.6+ 最好的方式:
name = "陈默"age = 25score = 92.567# 基本用法print(f"我叫{name},今年{age}岁") # 输出: 我叫陈默,今年25岁# 表达式print(f"明年我{age + 1}岁") # 输出: 明年我26岁print(f"名字长度:{len(name)}") # 输出: 名字长度:2# 格式化数字print(f"分数:{score:.1f}") # 输出: 分数:92.6(保留1位小数)print(f"分数:{score:.2f}") # 输出: 分数:92.57(保留2位小数)print(f"数字:{42:05d}") # 输出: 数字:00042(补零到5位)print(f"百分比:{0.856:.1%}") # 输出: 百分比:85.6%
常用格式化符号
num = 3.14159print(f"{num:.2f}") # 输出: 3.14(2位小数)print(f"{num:.4f}") # 输出: 3.1416(4位小数)print(f"{1000:,}") # 输出: 1,000(千位分隔符)print(f"{0.5:.2%}") # 输出: 50.00%(百分比)print(f"{42:08d}") # 输出: 00000042(补零)print(f"{'hello':>10}") # 输出: hello(右对齐)print(f"{'hello':<10}") # 输出: hello (左对齐)print(f"{'hello':^10}") # 输出: hello (居中)
format():老写法
Python 3.6 之前的写法,了解即可:
name = "陈默"age = 25print("我叫{},今年{}岁".format(name, age)) # 输出: 我叫陈默,今年25岁print("我叫{0},今年{1}岁".format(name, age)) # 输出: 我叫陈默,今年25岁print("我叫{n},今年{a}岁".format(n=name, a=age))
3. 输入:input() 从键盘拿数据
基本用法
name = input("请输入你的名字:")print(f"你好,{name}!")# 运行时:# 请输入你的名字:陈默# 你好,陈默!
input() 返回的永远是字符串。
类型转换
如果你想拿到数字,得手动转:
# 拿到整数age = int(input("请输入年龄:"))print(f"10年后你{age + 10}岁")# 拿到浮点数height = float(input("请输入身高(米):"))print(f"你的身高是{height}米")# 拿到多个值a, b = input("请输入两个数字(空格分隔):").split()a, b = int(a), int(b)print(f"和:{a + b}")
输入验证
用户可能乱输入,你得防着:
whileTrue: age = input("请输入年龄:")if age.isdigit(): age = int(age)break print("请输入有效的数字!")print(f"你的年龄是{age}岁")
# 更健壮的验证defget_number(prompt, min_val=None, max_val=None):whileTrue:try: value = float(input(prompt))if min_val isnotNoneand value < min_val: print(f"不能小于{min_val}")continueif max_val isnotNoneand value > max_val: print(f"不能大于{max_val}")continuereturn valueexcept ValueError: print("请输入有效的数字")age = get_number("请输入年龄(1-150):", 1, 150)print(f"你的年龄是{int(age)}岁")
4. 命令行参数:sys.argv
脚本运行时从命令行拿参数:
# script.pyimport sysprint(f"脚本名:{sys.argv[0]}")print(f"参数列表:{sys.argv}")print(f"参数个数:{len(sys.argv) - 1}")
python script.py hello world 123# 输出:# 脚本名:script.py# 参数列表:['script.py', 'hello', 'world', '123']# 参数个数:3
实用的命令行工具
import sysdefmain():if len(sys.argv) != 3: print("用法:python calc.py <数字1> <数字2>") sys.exit(1) a = float(sys.argv[1]) b = float(sys.argv[2]) print(f"加:{a + b}") print(f"减:{a - b}") print(f"乘:{a * b}") print(f"除:{a / b:.2f}")if __name__ == "__main__": main()
python calc.py 10 3# 输出:# 加:13.0# 减:7.0# 乘:30.0# 除:3.33
5. 标准输入输出重定向
输出重定向
import sys# 保存原始输出original_stdout = sys.stdout# 重定向到文件with open("output.txt", "w") as f: sys.stdout = f print("这行会写入文件") print("这行也会")# 恢复原始输出sys.stdout = original_stdoutprint("这行显示在屏幕上")
用 contextlib 更优雅
from contextlib import redirect_stdoutwith open("output.txt", "w") as f:with redirect_stdout(f): print("写入文件") print("这也写入文件")print("回到屏幕")
6. 美化输出
对齐表格
students = [ ("陈默", 85, "优秀"), ("小明", 42, "补考"), ("小红", 91, "优秀"), ("小李", 78, "良好"),]# 表头print(f"{'姓名':<6}{'分数':>4}{'等级':<4}")print("-" * 18)# 数据行for name, score, grade in students: print(f"{name:<6}{score:>4}{grade:<4}")# 输出:# 姓名 分数 等级# ------------------# 陈默 85 优秀# 小明 42 补考# 小红 91 优秀# 小李 78 良好
进度条
import timedefprogress_bar(total):for i in range(total + 1): percent = i / total bar = "█" * int(50 * percent) + "░" * (50 - int(50 * percent)) print(f"\r[{bar}] {percent:.0%}", end="") time.sleep(0.02) print()progress_bar(100)# 输出: [██████████████████████████████████████████████████] 100%
\r 让光标回到行首,覆盖之前的内容,形成动画效果。
7. 实战:交互式计算器
defcalculator():"""一个交互式的计算器""" print("=" * 30) print(" 简易计算器(输入 q 退出)") print("=" * 30)whileTrue: print("\n操作:+ - * /") op = input("请选择操作:").strip()if op.lower() == "q": print("再见!")breakif op notin ["+", "-", "*", "/"]: print("无效操作,请重新选择")continuetry: a = float(input("第一个数:")) b = float(input("第二个数:"))except ValueError: print("请输入有效的数字")continueif op == "+": result = a + belif op == "-": result = a - belif op == "*": result = a * belif op == "/":if b == 0: print("不能除以零!")continue result = a / b print(f"结果:{a}{op}{b} = {result}")if __name__ == "__main__": calculator()
最后
输入和输出看起来简单,但它是程序和世界交互的接口。
记住三件事:
input() 返回的是字符串,需要数字要手动转换
我的建议:
写一个交互式的小程序——记账本、BMI 计算器、单词记忆工具。让它能接收你的输入,处理之后给出输出。
程序的价值不在于它能算多快,而在于它能和人对话。
今天就到这里。
我是陈默,我们下期再见。
如果你觉得这篇文章有帮助,欢迎关注我。我会持续分享 Python 学习的干货。