我如何理解如何将代码重构为函数以供将来使用

How do I understand how to refactor code in to functions for future use

我正在 class 使用 Python 速成课程文本。 class 本来应该是面对面的,但已经转移到网上了。我对以下作业感到困惑,想知道是否有人可以帮助我完成它。

重构代码是将部分代码转换为可在代码的其他部分再次使用的函数的过程。

在之前的作业“测试成绩更有趣”中,您应该确定是否有人得了 100 分。您将提取代码中用于确定是否有人得了 100 分的部分并将其转换为函数称为 has_100()(5 分)。想想你的函数可能需要什么参数,你的函数需要什么数据类型 return。 has_100() 函数不需要打印任何信息。它只需要查看成绩列表和 return True 或 False,具体取决于列表是否包含 100。

您还需要创建一个名为 print_top_grades() 的函数。为了使这个函数可重用,它应该有几个参数; (1) 要打印的成绩数和 (2) 包含成绩的列表。这将不同于 has_100() 函数,因为 print_top_grades() 不会 return 任何东西。它只是使用 for 循环按降序打印列表中的前 n 个成绩。注意:由于列表是可变的,因此您必须注意不要对列表进行永久排序。您只想打印前 n 个成绩。

一定要考虑到一个空列表。 如果要打印的成绩数大于列表中的成绩数,则应按降序打印所有成绩。例如,如果列表中有 3 个成绩但有人试图打印前 5 个成绩,则应只打印 3 个成绩。

#more fun with test grades assignment
# Do not modify: required for assignment
import random
last_score = random.randint(99,100)
if bool(random.getrandbits(1)):
    grades = [71, 64, 82, 72, 56, 99, 96, 99, 86, 84, 90, last_score]
else:
    grades = []
# Do not modify: required for assignment

赋值很简单,而不是不使用函数编写整个逻辑(像现在这样写)你需要将代码分成函数。

应该是这样的:

def has_100():
    """Identifies if anyone scored a 100"""
    # your code here

def print_top_grades():
    """print the top n grades in the list in descending order"""
    # your code here

def main():
    """Here you will write the execution of the program
    reusing the functions above according to the task assigned"""
    # your code here

# This is used to execute our file when you call 'python file.py' in your 
# terminal
if __name__ == '__main__':
    main()

将您需要的参数添加到函数中(但不添加到 main() 中)以完成每个函数的任务。