【kaggle 课程】Python

help查看函数描述,自己写的函数描述在```里面叫做文档字符串

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.
    
    >>> least_difference(1, 5, -5)
    4
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)

help(least_difference)结果:

Help on function least_difference in module __main__:

least_difference(a, b, c)
    Return the smallest difference between any two numbers
    among a, b and c.
    
    >>> least_difference(1, 5, -5)
    4

默认参数默认参数

当我们调用 help(print) 时,我们看到 print 函数有几个可选参数。例如,我们可以为 sep 指定一个值,以便在打印的参数之间放置一些特殊字符串:

print(1, 2, 3, sep=' < ')

结果:

1 < 2 < 3

但是,如果我们不指定值,则 sep 将被视为具有默认值 ’ '(单个空格)。

函数作为参数

应用于函数的函数
这是一个很强大的东西,虽然一开始它会感觉很抽象。您可以将函数作为参数提供给其他函数。一些例子可能会使这一点更清楚:

def mod_5(x):
    """Return the remainder of x after dividing by 5"""
    return x % 5

print(
    'Which number is biggest?',
    max(100, 51, 14),
    'Which number is the biggest modulo 5?',
    max(100, 51, 14, key=mod_5),
    sep='\n',
)

结果:

5
25

round

help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.
    解决方案:如您所见,ndigits=-1 舍入到最接近的 10,ndigits=-2 舍入到最接近的 100,依此类推。
    这可能在哪里有用?假设我们正在处理大量数字:338,424
    我们可以通过使用 ndigits=-3 调用 round() 来删除它们:338,000

猜你喜欢

转载自blog.csdn.net/weixin_43154149/article/details/124674771