目录
变量定义
Python是动态类型语言,变量声明时无需指定类型:
a = 0 # 整型 (int)
s = "string" # 字符串 (str)
b = True # 布尔型 (bool)
l = ["s", 1, True] # 列表 (list) 可包含混合类型
输入输出
输入处理
i = input() # 默认返回字符串类型
values = input().split() # 按空格分割为列表
x, y, z = input().split() # 解包为三个字符串变量
输出处理
print("Hello World!") # 自动换行(默认 end='\n')
print("No newline", end="") # 禁止自动换行
print(f"变量i的值:{i}") # 推荐使用f-string格式化
print("注意:" + error_msg) # 字符串拼接需类型一致
条件判断
多条件判断结构
num = int(input("请输入数字:"))
flag = True
if 10 <= num < 100: # Python特色链式比较
print("两位数")
elif num < 10 or num >= 100: # 逻辑运算符 or/and
flag = False
print("非两位数范围")
elif flag: # 直接判断布尔值
print(f"当前标志:{flag}")
else:
print("异常情况")
循环结构
While循环
count = 5
while count > 0:
print(f"倒计时:{count}")
count -= 1
For循环
fruits = ["apple", "banana", "cherry"]
# 遍历列表元素
for fruit in fruits:
print(fruit)
# 带索引遍历
for idx, fruit in enumerate(fruits):
print(f"索引 {idx}: {fruit}")
# 范围循环
for i in range(3, 0, -1): # 从3到1倒序
print(i)
函数定义
基础函数示例
def progress_bar(current, total, width=20) -> bool:
"""显示进度条
:param current: 当前进度
:param total: 总进度
:param width: 进度条长度
:return: 是否完成
"""
ratio = min(current / total, 1.0)
filled = int(ratio * width)
bar = '█' * filled + '-' * (width - filled)
print(f'\r[{bar}] {ratio:.1%}', end='')
if current >= total:
print() # 换行
return current >= total
类与对象
类定义与生命周期
class ProgressVisualizer:
"""进度可视化工具类"""
def __init__(self, total_width=20):
"""构造函数,初始化实例属性"""
self.width = total_width
print("进度器初始化完成")
def show_progress(self, current, total):
"""显示进度条
:param current: 当前进度值
:param total: 总进度值
"""
progress = min(current / total, 1.0)
filled = int(progress * self.width)
bar = '█' * filled + '░' * (self.width - filled)
print(f'\r[{bar}] {progress:.1%}', end='')
def __del__(self):
"""析构函数,对象销毁时自动调用"""
print("\n进度器已释放")
if __name__ == "__main__":
# 类使用示例
pv = ProgressVisualizer(30)
pv.show_progress(75, 100)