如何正确格式化python代码结构?

时间:2018-12-06 17:34:01

标签: python python-3.x formatting

我对python还是有点陌生​​,我正在尝试学习如何为现实世界的应用程序和访谈正确格式化我的代码。

下面的代码以数字作为输入,然后返回列表中给定数字的上方和下方的数字。我创建了一个类placeOfNum,用于存储函数Solution,该函数执行所有处理逻辑。

如果我想像下面那样输出答案,最好的做法是像下面那样调用answer类函数,还是应该将所有内容都保留在类中以提高可读性,还是应该另做一个?函数,例如在类中使用def placeOfNum(self, n, array): aboveNum = 0 belowNum = 0 array = sorted(array) for x in array: if x < n: belowNum += 1 if x > n: aboveNum += 1 return (above, below) numList = [1,5,21,2,1,10,232] num = 21 x = Solution() answer = x.placeOfNum(num, numList) print("above:", answer[0], "below:", answer[1]) # returns "above:1, below:5" 并在该类中输出解决方案?

Select e.ename
from emp e 
where e.job = "MANAGER" 
    and e.mgr not in (select empno from emp where job = "MANAGER")

1 个答案:

答案 0 :(得分:1)

def place_of_num(num, array):
    above_num = 0 
    below_num = 0

    for x in array: 
        if x < num: 
            below_num += 1
        if x > num: 
            above_num += 1
    return tuple((above_num, below_num))

num_list = sorted([1,5,21,2,1,10,232])
num = 21

answer = place_of_num(num, num_list)
print(f"above: {answer[0]} and below: {answer[1]}")

我会这样写的。保持命名的一致性,就像对变量,函数和对于类名使用CamelCase一样使用snake_case。保持代码简单易读