代码理解
我们希望遇到的都是注释丰富的代码,易于理解,易于解读,拓展方便。因为我们看一段代码都是习惯优先看自然语言,好的代码注释会更快帮助我们理解代码。比如这样的代码:
# 计算器
# 支持加、减、乘、除运算
# 定义加法函数
def add(a, b):
return a + b
# 定义减法函数
def subtract(a, b):
return a - b
# 定义乘法函数
def multiply(a, b):
return a * b
# 定义除法函数并处理除零错误
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Can't divide by zero!"
# 显示欢迎信息
print("Welcome to the calculator!")
但可能经常碰到没有注释的代码,比如这样的:
def rfm_user(df):
if df['M_score'] == 1 and df['R_score'] == 1 and df['F_score'] ==
1:
return '重要价值用户'
if df['M_score'] == 1 and df['R_score'] == 1 and df['F_score'] ==
0:
return '重要发展用户'
if df['M_score'] == 1 and df['R_score'] == 0 and df['F_score'] ==
1:
return '重要保持用户'
if df['M_score'] == 1 and df['R_score'] == 0 and df['F_score'] ==
0:
return '重要挽留用户'
if df['M_score'] == 0 and df['R_score'] == 1 and df['F_score'] ==
1:
return '一般价值用户'
if df['M_score'] == 0 and df['R_score'] == 1 and df['F_score'] ==
0:
return '一般发展用户'
时间久了,有时候自己也忘了是啥逻辑了,当然别人来看更是一脸懵逼。
TIPS:我们丢给chatGPT,后面带上代码解释四个字得到以下结果:
再比如
def sort_point(points):
sp = sorted(points, key=lambda x: (int(x[1]), int(x[0])))
if sp[0][0] > sp[1][0]:
sp[0], sp[1] = sp[1], sp[0]
if sp[2][0] > sp[3][0]:
sp[2], sp[3] = sp[3], sp[2]
return sp
Tips:当解释不够详细时,可以通过让ChatGPT给你举个例子,会更容易理解, 比如上面例子
实际运用下:
得到如下解释:
代码注释
为了赶进度,我们的代码可能是这样的
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
if __name__ == "__main__":
arr = [3, 5, 2, 7, 6, 1, 4]
insertion_sort(arr)
print(arr)
我们丢给chatGPT,让他做代码注释,得到以下结果:
但是感觉代码不够详细,继续输入指令请给出详细的注释:
让他教我快速搭建了项目,构建了页面,中间也会有编译不过的情况,把报错信息贴给他,也会帮你改bug,谁用谁知道~