Article Directory
Overview
Python has a lot of functions, we learned in the previous section, print
and abs
so on built-in functions.
And custom functions are also a very important part of Python. This section mainly learned the definition and use of functions.
Getting help
When we forget the usage of a function, the help()
function can help us understand other functions.
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如果不等于None或者没被省略,roungd返回的类型就是,与ndigits规定的数字有关。
'''
help()
Two-part results
- The header of the function, in this example
round(number[, ndigits])
, it tells us that theround
function accepts onenumber
, and we can also choose a row to give a different parameterndigits
. (ndigits
Here means a few digits after the decimal point) - A brief description of the function of the equation.
Common pitfall : When we query a function, we need to query the name of the function abs
, not calling that function abs()
.
help(round(-2.01))
# 结果显示了很多关于整数的内容
Python calculates an expression from the inside out . So in the above expression, first calculate round(-2.01)
, and then query (help) round(-2.01)
the result (output of that expression).
round
The function is a simple function with short DocStrings. In the following study, we will deal with some more complex and configurable (configurable) functions, for example print
. When encountering some inscrutable docstrings, we have to learn to extract some new knowledge from them.
help(print)
'''
Help on built-in function print in module builtins(模块内置命令):
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.
'''
We can see that the print
function can accept a variable sep
, which represents what print
is placed in the variable when we have other variables.
Defining functions
def least_difference(a, b, c):
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
The above defined function module least_difference
, he has three parameters a
, b
, and c
.
Define the function def
as the header, followed by the indented block :
.
return
Is another keyword uniquely associated with the function. When Python encounters a return
statement, it immediately exits the function and return
calls the value on the right into the context.
example:
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)
# 9 0 1
In addition, we can try to help
explain our definition with a function least_difference
:
help(least_difference)
'''
Help on function least_difference in module __main__:
least_difference(a, b, c)
'''
From the above code, we can see that Python is not smart enough to give me a reasonable explanation for the function defined. So when we define a function, we can provide a description for this function, called a docstring .
Docstrings
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)
The docstring in the definition function is a triple-quoted string (it can consist of many lines), and its position starts at the first line under the function header.
When we call the help
function, the result shows the docstring.
help(least_difference)
'''
least_difference(a, b, c)
Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4
'''
The
>>>
is a reference to the command prompt(命令提示符) used in Python interactive shells.
The example in docstrings help someone understand the function.
Good programmers will use docstrings unless the equation will be lost later.
Functions that don't return (define an equation that does not contain return)
What happens if we don’t join when we are defining the equation return
?
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
min(diff1, diff2, diff3)
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)
# 结果:None None None
- Python allows us to define
return
functions that are not included and call the function displayNone
(this is similar to'null' in other functions). - No
return
functionleast_difference
is meaningless; but does not include a definition of functionreturn
in some cases also useful. We just callreturn
the function of nothing to output some text, or we can also write to a file and modify an input.
least_difference()
'''
返回结果报错:
--------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1fd5223251aa> in <module>
----> 1 least_difference()
TypeError: least_difference() missing 3 required positional arguments: 'a', 'b', and 'c'
'''
mystery = print()
print(mystery)
# 返回结果:None
Default argument
When we call help(print)
, we can see that the print
function has some optional arguments. For example, we can sep
specify a value for (specify a value).
print(1, 2, 3, sep=' < ')
# 1 < 2 < 3
But when we do not sep
specify a value for, it sep
is processed as having a default value ''(a single space)
print(1, 2, 3)
# 1 2 3
Add a parameter with a default value:
def greet(who="Colin"):
print("Hello,", who)
greet()
greet(who="Kaggle")
# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
greet("world")
'''
Hello, Colin
Hello, Kaggle
Hello, world
'''
Functions Applied to Functions (application of functions in functions)
We can provide functions as parameters to other functions.
def mult_by_five(x):
return 5 * x
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', # '\n' is the newline character - it starts a new line
)
# 5
# 25
\n
Newline charactermax
Function is addedkey
after, also known asargmax
(aka the 'argmax')- aka: also know as 又名
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',
)
'''
Which number is biggest?
100
Which number is the biggest modulo 5?
14
'''
pass
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code block, Python requires at least one line of code)
pass
pass
It has no effect in the function, we use it as a placeholder, because before we start a code block, Python needs at least one line of code.
round
round()
In the function, when ndigits = -1, -2… negative numbers, number is rounded round
to the nearest 10, 100…
round(123.12, ndigits = -1)
# 120.0
The area of Finland is 338,424 km²
The area of Greenland is 2,166,086 km²当 ndigits = -3
The area of Finland is 338,000 km²
The area of Greenland is 2,166,000 km²
round()
In the function, when ndigits = -1, -2… negative numbers, number is rounded round
to the nearest 10, 100…
round(123.12, ndigits = -1)
# 120.0
The area of Finland is 338,424 km²
The area of Greenland is 2,166,086 km²当 ndigits = -3
The area of Finland is 338,000 km²
The area of Greenland is 2,166,000 km²