以下是Python语言核心的15个必知语法细节,每个细节都附有相应的代码示例:
- 动态类型与变量赋值:
a = 10 # 整数
b = 3.14 # 浮点数
c = "Hello" # 字符串
d = [1, 2, 3] # 列表
- 变量命名规则:
# 正确的变量名
my_variable = 10
_another_var = 20
# 错误的变量名(以数字开头)
# 1_var = 30 # SyntaxError
- 字符串操作:
s = "Hello, World!"
print(s[0]) # 'H'(索引)
print(s[0:5]) # 'Hello'(切片)
print(s * 2) # 'Hello, World!Hello, World!'(重复)
- 列表与元组:
# 列表
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4](修改列表)
# 元组
tup = (1, 2, 3)
# tup.append(4) # AttributeError: 'tuple' object has no attribute 'append'(不可修改)
- 字典:
d = {'name': 'Alice', 'age': 25}
print(d['name']) # 'Alice'(通过键访问)
d['age'] = 26 # {'name': 'Alice', 'age': 26}(修改字典)
- 条件语句:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
- 循环语句:
# for循环
for i in range(5):
print(i)
# while循环
count = 0
while count < 5:
print(count)
count += 1
- 函数定义与调用:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # 'Hello, Alice!'
- 模块导入:
import math
print(math.sqrt(16)) # 4.0(导入math模块并使用其sqrt函数)
- 异常处理:
try:
result = 10 / 0 # 这将引发一个ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
- 列表解析:
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
- 生成器函数:
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
for value in gen:
print(value) # 1, 2, 3(逐个生成值)
- 面向对象编程(类与对象):
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
p = Person("Alice", 30)
print(p.greet()) # 'Hello, my name is Alice and I am 30 years old.'
- 文件操作:
# 写入文件
with open('example.txt', 'w') as file:
file.write("Hello, World!")
# 读取文件
with open('example.txt', 'r') as file:
content = file.read()
print(content) # 'Hello, World!'
- 代码注释:
# 这是一个单行注释
"""
这是一个多行注释(文档字符串)
它通常用于描述函数、类或模块的功能和用途。
"""
def example_function():
"""
这是一个示例函数的文档字符串。
"""
pass
这些代码示例展示了Python语言的核心语法细节,并通过实际代码帮助理解每个细节的用法。