# Python基本语句有哪些 Python作为一门简洁高效的编程语言,其核心语句体系是构建程序逻辑的基础。本文将系统介绍Python中的7大类基本语句,通过代码示例和实际应用场景帮助开发者掌握语法精髓。 ## 一、变量声明与赋值语句 ### 1. 基本赋值语句 Python使用等号(`=`)进行变量赋值,无需声明变量类型: ```python x = 10 # 整数赋值 name = "Alice" # 字符串赋值 pi = 3.14 # 浮点数赋值
支持同时为多个变量赋值:
a, b, c = 5, 10, 15 # 并行赋值 x = y = z = 0 # 链式赋值
适用于序列类型的数据解包:
coordinates = (12.5, 6.8) latitude, longitude = coordinates # 元组解包
score = 85 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' # 本例将执行此分支 else: grade = 'C'
count = 0 while count < 5: print(count) count += 1 # 输出0-4
for i in range(3): print(i) else: print("循环完成") # 正常结束后执行
def greet(name): """返回问候字符串""" return f"Hello, {name}!"
def calculate(a, b, operator='+'): if operator == '+': return a + b elif operator == '*': return a * b
square = lambda x: x ** 2 # 匿名函数
try: result = 10 / 0 except ZeroDivisionError: print("不能除以零!")
try: file = open('data.txt') except FileNotFoundError: print("文件未找到") else: content = file.read() file.close() finally: print("处理结束") # 无论是否异常都会执行
file = None try: file = open('example.txt', 'w') file.write("Hello World") finally: if file: file.close()
with open('data.csv', 'r') as f: lines = f.readlines() # 自动处理文件关闭
import math print(math.sqrt(16)) # 4.0
from collections import defaultdict from os.path import join as path_join
def divide(a, b): assert b != 0, "除数不能为零" return a / b
def todo_function(): pass # 占位符
lst = [1, 2, 3] del lst[1] # 删除索引1的元素
def clean_data(data): cleaned = [] for item in data: try: # 尝试转换为浮点数 num = float(item.strip()) if not math.isnan(num): cleaned.append(round(num, 2)) except (ValueError, TypeError): pass return sorted(cleaned)
class Timer: def __enter__(self): self.start = time.time() def __exit__(self, *args): print(f"耗时: {time.time()-self.start:.2f}s") with Timer(): time.sleep(1.5) # 自动输出执行时间
条件语句优化:
if x is None
而非if x == None
if lst and lst[0] == value
循环控制技巧:
for i, item in enumerate(items, start=1): if some_condition(item): break else: print("未找到符合条件的项")
异常处理原则:
Q:Python中switch-case如何实现? A:Python没有switch语句,可通过字典映射实现:
def case1(): return "处理情况1" def case2(): return "处理情况2" switch = {1: case1, 2: case2} result = switch.get(choice, lambda: "默认情况")()
Q:如何跳出多层循环? A:使用异常机制或标志变量:
class BreakOuterLoop(Exception): pass try: for i in range(10): for j in range(10): if condition(i,j): raise BreakOuterLoop except BreakOuterLoop: pass
掌握Python基本语句是编写高质量代码的基础。建议读者: 1. 在实际项目中多练习复合语句的使用 2. 阅读优秀开源代码学习语句组合技巧 3. 定期回顾语言官方文档保持知识更新
提示:Python之禅强调”简单优于复杂”,合理运用基本语句往往比复杂技巧更能体现Pythonic风格。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。