Python语法及常用用法(1)
- 1. 变量与数据类型:
- 2. 控制流程:
- 条件语句:
- 循环:
- 3. 函数:
- 4. 列表和字典:
- 5. 文件操作:
- 6. 异常处理:
- 7. 列表推导式:
- 8. 集合和元组:
- 9. 类与面向对象编程:
- 10. 模块和导入:
- 11. 装饰器:
- 12. Lambda表达式:
- 13. 生成器:
- 14. 迭代器和可迭代对象:
- 15. with语句和文件管理:
- 16. 列表切片:
- 17. 字符串格式化:
- 18. 字典推导式:
- 19. 异步编程(async/await):
- 20. 注解:
- 21. 枚举:
- 22. 特殊方法(魔法方法):
- 23. 命名空间和作用域:
- 24. eval:
- 25. 深拷贝和浅拷贝:
- 26. 装饰器链:
- 27. 链式比较:
- 28. 上下文管理器与`with`语句:
- 29. 元编程`exec()`:
- 30. 类属性与实例属性:
Python是一种易学、高级、通用的编程语言。以下是一些Python语法的基本要点:
1. 变量与数据类型:
# 定义变量
name = "John"
age = 25
height = 1.75
# 数据类型
string_type = "Hello, Python!"
int_type = 42
float_type = 3.14
bool_type = True
2. 控制流程:
条件语句:
if condition:
# code block if condition is True
elif another_condition:
# code block if another_condition is True
else:
# code block if no conditions are True
循环:
# for循环
for item in iterable:
# code block
# while循环
while condition:
# code block
3. 函数:
# 定义函数
def greet(name):
return f"Hello, {name}!"
# 调用函数
result = greet("Alice")
print(result)
4. 列表和字典:
# 列表
my_list = [1, 2, 3, "apple", "banana"]
# 字典
my_dict = {"name": "John", "age": 25, "city": "New York"}
5. 文件操作:
# 打开文件
with open("example.txt", "r") as file:
content = file.read()
# 写入文件
with open("output.txt", "w") as file:
file.write("Hello, Python!")
6. 异常处理:
try:
# 可能发生异常的的代码
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print("No exception occurred.")
# 没有异常发生时执行
finally:
print("Regardless of an exception.")
# 无论是否发生异常都执行
7. 列表推导式:
# 使用列表推导式创建列表
squares = [x**2 for x in range(1, 6)]
# 结果: [1, 4, 9, 16, 25]
8. 集合和元组:
# 集合
my_set = {1, 2, 3, 3, 4}
# 结果: {1, 2, 3, 4}
# 元组
my_tuple = (1, "apple", 3.14)
9. 类与面向对象编程:
# 定义类
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# 创建对象
my_dog = Dog("Buddy", 3)
# 调用对象方法
my_dog.bark()
10. 模块和导入:
# 创建自定义模块(example_module.py)
# def greet(name):
# return f"Hello, {name}!"
# 导入模块
import example_module
# 使用模块中的函数
result = example_module.greet("Alice")
print(result)
11. 装饰器:
# 定义装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
# 使用装饰器
@my_decorator
def say_hello():
print("Hello!")
say_hello()
12. Lambda表达式:
# 使用Lambda表达式创建匿名函数
add = lambda x, y: x + y
result = add(3, 5)
# 结果: 8
13. 生成器:
# 使用生成器创建迭代器
def my_generator(n):
for i in range(n):
yield i
# 使用生成器
gen = my_generator(3)
for num in gen:
print(num)
# 结果: 0, 1, 2
14. 迭代器和可迭代对象:
# 可迭代对象
my_list = [1, 2, 3, 4, 5]
my_iter = iter(my_list)
# 迭代器
while True:
try:
item = next(my_iter)
print(item)
except StopIteration:
break
15. with语句和文件管理:
# 使用with语句处理资源管理
with open("example.txt", "r") as file:
content = file.read()
# 文件自动关闭,即使发生异常
16. 列表切片:
# 使用切片进行列表操作
my_list = [1, 2, 3, 4, 5]
subset = my_list[1:4]
# 结果: [2, 3, 4]
17. 字符串格式化:
# 字符串格式化
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I'm {age} years old."
# 结果: "My name is Alice and I'm 30 years old."
18. 字典推导式:
# 字典推导式
my_dict = {x: x**2 for x in range(5)}
# 结果: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
19. 异步编程(async/await):
# 异步函数
import asyncio
async def my_async_function():
print("Start")
await asyncio.sleep(1)
print("End")
# 运行异步函数
asyncio.run(my_async_function())
20. 注解:
# 函数注解
def add_numbers(a: int, b: int) -> int:
return a + b
21. 枚举:
# 使用枚举
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
# 结果: Color.RED
22. 特殊方法(魔法方法):
# 特殊方法示例
class MyClass:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"MyClass({self.value})"
obj = MyClass(42)
print(obj)
# 结果: MyClass(42)
23. 命名空间和作用域:
# 命名空间和作用域
global_var = 10
def my_function():
local_var = 5
print(global_var)
print(local_var)
my_function()
24. eval:
# 使用eval执行动态代码
expression = "3 + 5 * 2"
result = eval(expression)
print(result)
# 结果: 13
25. 深拷贝和浅拷贝:
# 深拷贝和浅拷贝
import copy
original_list = [1, [2, 3], [4, 5]]
shallow_copy = copy.copy(original_list)
deep_copy = copy.deepcopy(original_list)
26. 装饰器链:
# 装饰器链
def uppercase_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase_decorator
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# 结果: HELLO, ALICE!
27. 链式比较:
# 链式比较
x = 5
print(1 < x < 10)
# 结果: True
28. 上下文管理器与with
语句:
# 上下文管理器示例
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
# 使用with语句
with MyContextManager() as context:
print("Inside the context")
29. 元编程exec()
:
# 元编程示例
code = """
def greet(name):
return f"Hello, {name}!"
"""
exec(code)
result = greet("Alice")
print(result)
# 结果: Hello, Alice!
30. 类属性与实例属性:
# 类属性与实例属性
class MyClass:
class_variable = "I am a class variable"
def __init__(self, instance_variable):
self.instance_variable = instance_variable
obj1 = MyClass("Instance 1")
obj2 = MyClass("Instance 2")
print(obj1.class_variable) # 访问类属性
print(obj1.instance_variable) # 访问实例属性