# 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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。