需要建议清理我的代码以使其干燥

Need advice cleaning my code to make it DRY

我正在做一个练习,我需要在那里创建一个代码,我将速度限制设置为 70m/h。 每增加 5 英里,代码将增加 1 分,5 分后许可证将被吊销。

我编写代码的方式可行,但重复性太强,我想不出一种方法可以通过循环使它变得更简单,而不必重复那么多次。

有什么建议吗?

def speed_check(speed):
    speed_limit = 70
    points = 0

    if speed <= speed_limit:
        return "Speed is OK"
    elif (speed < speed_limit + 5) and (speed > speed_limit):
        points += 1
        return "Points taken {}!".format(points)
    elif (speed < speed_limit + 10) and (speed > speed_limit):
        points += 2
        return "Points taken {}!".format(points)
    elif (speed < speed_limit + 15) and (speed > speed_limit):
        points += 3
        return "Points taken {}!".format(points)
    elif (speed < speed_limit + 20) and (speed > speed_limit):
        points += 4
        return "Points taken {}!".format(points)
    else:
        points += 5
        return "Points taken {}!\nYour license has been revoked".format(points)


your_speed = int(input("Enter speed: "))
print(speed_check(your_speed))

import math

def speed_check(speed):
    speed_limit = 70
    points = 0

    if speed > speed_limit:
      amountOverSpeedLimit = (speed - speed_limit)
      points = math.floor(amountOverSpeedLimit/5)

    return "Points taken {}!".format(points)

your_speed = int(input("Enter speed: "))
print(speed_check(your_speed))

您可以使用 math.floor 和一些除法来获得相同的结果。当你超过 4 点或当你的速度没有超过限制时,这不能解决消息,但你应该能够添加它。