0. 变量和赋值:
x = 5
name = "John"
1. 数据类型:
整数(int)
浮点数(float)
字符串(str)
布尔值(bool)
2. 注释:
python
# 这是单行注释
"""
这是
多行注释
"""
3. 算术运算:
python
a + b # 加法
a - b # 减法
a * b # 乘法
a / b # 除法
a % b # 取余
a ** b # 幂运算
4. 比较运算:
python
a == b # 等于
a != b # 不等于
a > b # 大于
a < b # 小于
a >= b # 大于等于
a <= b # 小于等于
5. 逻辑运算:
python
a and b
a or b
not a
6. 条件语句:
python
if condition:
# do something
elif another_condition:
# do something else
else:
# do something different
7. 循环:
python
for i in range(5):
print(i)
while condition:
# do something
8. 列表:
python
my_list = [1, 2, 3]
my_list.append(4)
my_list[0] # 访问元素
9. 元组:
python
my_tuple = (1, 2, 3)
10. 字典:
python
my_dict = {"name": "John", "age": 30}
my_dict["name"] # 访问键值
11. 集合:
python
my_set = {1, 2, 3}
my_set.add(4)
12. 字符串操作:
python
s = "hello"
s.upper()
s.lower()
s.split(" ")
s.replace("h", "j")
13. 字符串格式化:
python
name = "John"
age = 30
f"Hello, {name}. You are {age}."
14. 列表解析:
python
squares = [x**2 for x in range(10)]
15. 函数定义:
python
def my_function(param1, param2):
return param1 + param2
16. 默认参数:
python
def my_function(param1, param2=5):
return param1 + param2
17. 关键字参数:
python
def my_function(param1, param2):
return param1 + param2
my_function(param2=10, param1=5)
18. 可变参数:
python
def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3)
19. 关键字可变参数:
python
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="John", age=30)
20. lambda表达式:
python
f = lambda x: x**2
f(5)
21. map函数:
python
list(map(lambda x: x**2, range(10)))
22. filter函数:
python
list(filter(lambda x: x % 2 == 0, range(10)))
23. reduce函数:
python
from functools import reduce
reduce(lambda x, y: x + y, range(10))
24. 异常处理:
python
try:
# do something
except Exception as e:
print(e)
finally:
# cleanup
25. 文件读取:
python
with open("file.txt", "r") as file:
content = file.read()
26. 文件写入:
python
with open("file.txt", "w") as file:
file.write("Hello, World!")
27. 类定义:
python
class MyClass:
def __init__(self, param1):
self.param1 = param1
def my_method(self):
return self.param1
28. 类继承:
python
class MyBaseClass:
def __init__(self, param1):
self.param1 = param1
class MyDerivedClass(MyBaseClass):
def __init__(self, param1, param2):
super().__init__(param1)
self.param2 = param2
29. 魔法方法:
python
class MyClass:
def __init__(self, param1):
self.param1 = param1
def __str__(self):
return f"MyClass with param1={self.param1}"
30. 属性和装饰器:
python
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
31. 生成器:
python
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
32. 列表解析和生成器表达式:
python
[x**2 for x in range(10)]
(x**2 for x in range(10))
33. 集合解析:
python
{x**2 for x in range(10)}
34. 字典解析:
python
{x: x**2 for x in range(10)}
35. 上下文管理器:
python
with open("file.txt", "r") as file:
content = file.read()
36. 装饰器:
python
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def my_function():
print("Function call")
my_function()
37. 类型注解:
python
def my_function(param1: int, param2: str) -> str:
return param2 * param1
38. 枚举:
python
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
39. 迭代器:
python
class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
40. JSON解析:
python
import json
json_str = '{"name": "John", "age": 30}'
data = json.loads(json_str)
41. 日期和时间:
python
from datetime import datetime
now = datetime.now()
42. 随机数生成:
python
import random
random_number = random.randint(1, 10)
43. 数学运算:
python
import math
math.sqrt(16)
44. 模块和包:
python
# my_module.py
def my_function():
return "Hello"
# main.py
import my_module
my_module.my_function()
45. 命名空间:
python
global_var = 5
def my_function():
local_var = 10
global global_var
global_var = 20
46. 继承和多态:
python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
47. 操作系统交互:
python
import os
os.getcwd()
os.listdir(".")
48. 命令行参数:
python
import sys
for arg in sys.argv:
print(arg)
49. 正则表达式:
python
import re
pattern = r"\d+"
re.findall(pattern, "There are 2 apples and 5 bananas.")