1. 输出 (Output)
1.1 print()
基础
Python 使用 print()
函数向控制台输出内容。
# 输出字符串
print("Hello, World!")
# 输出多个值(自动用空格分隔)
print("Name:", "Alice", "Age:", 25)
# 修改分隔符(sep参数)
print("2023", "12", "31", sep="-") # 输出: 2023-12-31
# 修改结束符(默认是换行)
print("Hello", end=" ")
print("World!") # 输出: Hello World!
1.2 格式化输出
方式 1: f-string (Python 3.6+ 推荐)
name = "Alice"
age = 30
print(f"{name} is {age} years old.") # Alice is 30 years old.
# 格式化数字
pi = 3.1415926
print(f"Pi: {pi:.2f}") # 保留两位小数 → Pi: 3.14
方式 2: format()
方法
print("{} + {} = {}".format(5, 3, 5+3)) # 5 + 3 = 8
print("{1} comes before {0}".format("Zebra", "Apple")) # 按索引 → Apple comes before Zebra
方式 3: 旧式 % 格式化
print("Score: %05d, Rate: %.2f%%" % (98, 85.333)) # Score: 00098, Rate: 85.33%
2. 输入 (Input)
2.1 input()
函数
input()
从用户获取输入,返回字符串类型:
name = input("Enter your name: ")
print(f"Hello, {name}!")
2.2 类型转换
输入内容默认是字符串,需转换为其他类型:
# 转换为整数
age = int(input("Enter your age: "))
# 转换为浮点数
height = float(input("Enter height (meters): "))
# 多个输入(用 split() 分割)
x, y = map(int, input("Enter two numbers: ").split())
print("Sum:", x + y)
总结
-
输出:使用
print()
和格式化方法(推荐 f-string) -
输入:
input()
+ 类型转换,注意错误处理
练习
编写程序询问用户姓名和年龄,输出格式化信息