今天主要从以下网站进行学习
https://www.kaggle.com/code/wangyumei/exercise-syntax-variables-and-numbers/edit
https://www.kaggle.com/code/colinmorris/functions-and-getting-help/tutorial
发现print函数的定义还挺有趣的,之前完全没意识到
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
有被安利到help(function)函数以及docstring撰写的必要性,给个例子真的非常有利于代码的理解,以后写代码要有这个意识:
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)
Functions Applied to Functions
def mult_by_five(x):
return x * 5
def call(fn, arg):
""" Call fn on arg """
return fn(arg)
def squared_call(fn, arg):
"""Call fn on the result of calling fn on arg"""
return fn(fn(arg))
print(
call(mult_by_five, 1),
squared_call(mult_by_five, 1),
sep='\n'
)
By default, max returns the largest of its arguments. But if we pass in a function using the optional key argument, it returns the argument x that maximizes key(x) (aka the ‘argmax’).
def mod_5(x):
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',
)
Round
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.
As you’ve seen, ndigits=-1 rounds to the nearest 10, ndigits=-2 rounds to the nearest 100 and so on. Where might this be useful? Suppose we’re dealing with large numbers:
The area of Finland is 338,424 km²
The area of Greenland is 2,166,086 km²
We probably don’t care whether it’s really 338,424, or 338,425, or 338,177. All those digits of accuracy are just distracting. We can chop them off by calling round() with ndigits=-3:
The area of Finland is 338,000 km²
The area of Greenland is 2,166,000 km²
完成https://www.kaggle.com/code/wangyumei/exercise-functions-and-getting-help/edit