Coursera 笔记

Module 01 · Python Coding Practices and Packaging Concepts

Hands-on Lab: Static Code Analysis动手实验:静态代码分析

In this lab, you will use the Theia IDE to perform static code analysis.

📄 Hands-on Lab- Static Code Analysis.pdf

可以的,这个例子很好练手 👍

你现在遇到的每一个 pylint 提示,其实都可以直接在这段代码里改掉。我们一条条来看,然后给出最终满分版本。


1. Missing module docstring(缺少模块文档字符串)

sample2.py:1:0: C0114: Missing module docstring

怎么改?

在文件最开头加上一段三引号的说明文字,比如:

"""Simple example module that adds two numbers and prints the result."""


2. Missing function docstring(缺少函数文档字符串)

sample2.py:3:0: C0116: Missing function or method docstring

怎么改?

在函数定义里面第一行加上 docstring:

def add(number1, number2):
    """Return the sum of two numbers."""
    return number1 + number2


3. Constant name "num2" / "total" doesn't conform to UPPER_CASE

  • num2
  • total

因为它们写在模块顶层,pylint 会默认它们是“常量”,所以要求全大写。

有两种做法:

  1. 把它们当常量用 → 改成大写
  2. 把它们移进函数 / main 里 → 变成局部变量

这题最简单的方式就是选第 1 种:改名为大写。

NUM1 = 4
NUM2 = 5
TOTAL = add(NUM1, NUM2)


4. consider-using-f-string(建议用 f-string)

C0209: Formatting a regular string which could be a f-string

原来的写法是:

print("The sum of {} and {} is {}".format(NUM1, num2, total))

用 f-string 更简洁,也符合 pylint 建议:

print(f"The sum of {NUM1} and {NUM2} is {TOTAL}")


综合之后的“满分版本”代码

直接把你的 sample2.py 改成下面这样,再跑一次 pylint sample2.py 就应该是 10/10 了:

"""Simple example module that adds two numbers and prints the result."""

def add(number1, number2):
    """Return the sum of two numbers."""
    return number1 + number2

# Constants are written in uppercase to indicate that they should not be changed.
NUM1 = 4
NUM2 = 5

# Call the 'add' function with 'NUM1' and 'NUM2' as arguments.
TOTAL = add(NUM1, NUM2)

# Print the result using an f-string.
print(f"The sum of {NUM1} and {NUM2} is {TOTAL}")


如果你愿意,你可以把 pylint 的输出贴出来(改完之后的),我可以帮你一起看还有没有其他隐藏的小问题。