# Python基本語法舉例分析
Python作為當前最流行的編程語言之一,以其簡潔優雅的語法和強大的功能受到廣泛歡迎。本文將通過具體示例分析Python的核心語法結構,幫助讀者快速掌握Python編程基礎。
## 一、變量與數據類型
### 1.1 變量定義
Python是動態類型語言,變量無需聲明類型:
```python
name = "Alice" # 字符串
age = 25 # 整數
height = 1.68 # 浮點數
is_student = True # 布爾值
類型 | 示例 | 說明 |
---|---|---|
int | x = 42 |
整數 |
float | pi = 3.14159 |
浮點數 |
str | s = "Python" |
字符串 |
bool | flag = True |
布爾值 |
list | lst = [1, 2, 3] |
可變序列 |
tuple | tup = (1, 2) |
不可變序列 |
dict | d = {'a': 1} |
鍵值對映射 |
set | s = {1, 2, 3} |
無序不重復元素集 |
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.333...
print(10 // 3) # 3 (整除)
print(10 % 3) # 1 (取模)
print(10 ** 3) # 1000 (冪運算)
print(5 > 3) # True
print(5 == 3) # False
print(5 != 3) # True
print(5 >= 5) # True
print(True and False) # False
print(True or False) # True
print(not True) # False
score = 85
if score >= 90:
print("優秀")
elif score >= 80:
print("良好") # 輸出此項
else:
print("繼續努力")
count = 0
while count < 5:
print(count)
count += 1
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for i in range(10):
if i == 3:
continue # 跳過本次循環
if i == 7:
break # 終止循環
print(i)
def greet(name):
"""返回問候語(文檔字符串)"""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# 默認參數
def power(x, n=2):
return x ** n
# 可變參數
def sum_all(*args):
return sum(args)
# 關鍵字參數
def person_info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.insert(1, 5) # [1, 5, 2, 3, 4]
numbers.remove(2) # [1, 5, 3, 4]
print(numbers[1:3]) # 切片 [5, 3]
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
person["city"] = "Beijing" # 添加鍵值對
for key, value in person.items():
print(f"{key}: {value}")
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1, 2}
# 寫入文件
with open("test.txt", "w") as f:
f.write("Hello, Python!\n")
# 讀取文件
with open("test.txt", "r") as f:
content = f.read()
print(content)
import csv
# 寫入CSV
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
# 讀取CSV
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"發生錯誤: {e}")
else:
print("計算成功")
finally:
print("執行完畢")
class Dog:
# 類屬性
species = "Canis familiaris"
# 初始化方法
def __init__(self, name, age):
self.name = name # 實例屬性
self.age = age
# 實例方法
def bark(self):
return f"{self.name} says woof!"
# 創建實例
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
class Bulldog(Dog): # 繼承Dog類
def run(self, speed):
return f"{self.name} runs at {speed}km/h"
bulldog = Bulldog("Max", 2)
print(bulldog.bark()) # 繼承的方法
print(bulldog.run(10)) # 子類特有方法
# 導入整個模塊
import math
print(math.sqrt(16))
# 導入特定函數
from random import randint
print(randint(1, 100))
# 別名導入
import numpy as np
創建mymodule.py
:
def greeting(name):
print(f"Hello, {name}")
在其他文件中使用:
import mymodule
mymodule.greeting("Alice")
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
gen = (x**2 for x in range(10))
for num in gen:
print(num)
def my_decorator(func):
def wrapper():
print("裝飾器前置操作")
func()
print("裝飾器后置操作")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
本文通過大量實例展示了Python的核心語法特性。Python的簡潔語法使得開發者可以用更少的代碼表達復雜的邏輯,這也是其廣受歡迎的重要原因。建議讀者在實際編碼中多加練習,逐步掌握Python編程的精髓。 “`
(全文約1850字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。