pythonの関数---関数の適用

30698 ワード

各プログラミング言語には、関数の参加が必要であり、pythonも例外ではありません.関数は統合されたサブルーチンであり,アルゴリズム実現の最小メソッド単位であり,基本操作を完了する手段の集合である.プログラミングでは関数を柔軟に応用し、プログラム設計の簡単化を高めることができる.コードアプリケーションの多重化を実現する.コード読書の明確化を向上させる.コード開発の強健化を強化する.コード開発の効率化を加速させる.チーム開発の便利化を強化する.プログラム理解の複雑化を低減する.コードストレージの削減.要するに、関数は、機能や操作を実現するための独立した機能ブロックであり、値を返さなくてもよいし、1つの値を返すことができ、複数の値を返すことができるなどである.
一、内蔵関数を使用する:
1、簡単な組み込み関数の応用:
ヘルプの表示、absの関数情報の表示など、関数の機能や関数のパラメータなどの情報の取得
まず、コマンド端末からpythonを入力してpythonインタラクションモードに入ります.
次に、help関数を使用してabsのパラメータでヘルプを取得し、help(abs)を入力します.
次に、ヘルプ情報を表示します.この例では、
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.
(END)

パラメータの絶対値を返す
最後:この例では、関数を使用します.
>>> abs(9, -2)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: abs() takes exactly one argument (2 given)
>>> abs(-2)
2

入力したパラメータが2つある場合は、エラーが発生します.そうでない場合は正しいです.
2、少し複雑な内蔵関数の応用:
ヘルプの表示、関数の機能や関数のパラメータなどの情報の取得、例えばmaxの関数情報の表示
まず、コマンド端末からpythonを入力してpythonインタラクションモードに入ります.
次にmathモジュールをインポートし、help関数を使用してパラメータmaxでヘルプを取得し、help(max)を入力します.
次に、ヘルプ情報を表示します.この例では、
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
(END)

パラメータの最大値を返す
最後:この例では、関数を使用します.
>>> import math
>>> print('45, 23, 36, 21, 9, 99      :', max(45, 23, 36, 21, 9, 99))
45, 23, 36, 21, 9, 99      : 99

モジュールヘルプを表示できます.
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.8/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.
    
    acosh(x, /)
        Return the inverse hyperbolic cosine of x.
    
    asin(x, /)
        Return the arc sine (measured in radians) of x.
    
    asinh(x, /)
        Return the inverse hyperbolic sine of x.

atan(x, /)
        Return the arc tangent (measured in radians) of x.
    
    atan2(y, x, /)
        Return the arc tangent (measured in radians) of y/x.
        
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(x, /)
        Return the inverse hyperbolic tangent of x.
    
    ceil(x, /)
        Return the ceiling of x as an Integral.
        
        This is the smallest integer >= x.
    
    comb(n, k, /)
        Number of ways to choose k items from n items without repetition and without order.
        
        Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
        to zero when k > n.
        
        Also called the binomial coefficient because it is equivalent
        to the coefficient of k-th term in polynomial expansion of the
        expression (1 + x)**n.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
copysign(x, y, /)
        Return a float with the magnitude (absolute value) of x but the sign of y.
        
        On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.
    
    cos(x, /)
        Return the cosine of x (measured in radians).
    
    cosh(x, /)
        Return the hyperbolic cosine of x.
    
    degrees(x, /)
        Convert angle x from radians to degrees.
    
    dist(p, q, /)
        Return the Euclidean distance between two points p and q.
        
        The points should be specified as sequences (or iterables) of
        coordinates.  Both inputs must have the same dimension.
        
        Roughly equivalent to:
            sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
    
    erf(x, /)
        Error function at x.
    
    erfc(x, /)
        Complementary error function at x.
    
 exp(x, /)
        Return e raised to the power of x.
    
    expm1(x, /)
        Return exp(x)-1.
        
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(x, /)
        Return the absolute value of the float x.
    
    factorial(x, /)
        Find x!.
        
        Raise a ValueError if x is negative or non-integral.
    
    floor(x, /)
        Return the floor of x as an Integral.
        
        This is the largest integer <= x.
    
    fmod(x, y, /)
        Return fmod(x, y), according to platform C.
        
        x % y may differ.
    
    frexp(x, /)
        Return the mantissa and exponent of x, as pair (m, e).
        
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.

fsum(seq, /)
        Return an accurate floating point sum of values in the iterable seq.
        
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(x, /)
        Gamma function at x.
    
    gcd(x, y, /)
        greatest common divisor of x and y
    
    hypot(...)
        hypot(*coordinates) -> value
        
        Multidimensional Euclidean distance from the origin to a point.
        
        Roughly equivalent to:
            sqrt(sum(x**2 for x in coordinates))
        
        For a two dimensional point (x, y), gives the hypotenuse
        using the Pythagorean theorem:  sqrt(x*x + y*y).
        
        For example, the hypotenuse of a 3/4/5 right triangle is:
        
            >>> hypot(3.0, 4.0)
            5.0
    
    isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
        Determine whether two floating point numbers are close in value.
    rel_tol
            maximum difference for being considered "close", relative to the
            magnitude of the input values
          abs_tol
            maximum difference for being considered "close", regardless of the
            magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(x, /)
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(x, /)
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(x, /)
        Return True if x is a NaN (not a number), and False otherwise.
    
    isqrt(n, /)
        Return the integer part of the square root of the input.
    
    ldexp(x, i, /)
        Return x * (2**i).
      
        This is essentially the inverse of frexp().
    
    lgamma(x, /)
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x, [base=math.e])
        Return the logarithm of x to the given base.
        
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(x, /)
        Return the base 10 logarithm of x.
    
    log1p(x, /)
        Return the natural logarithm of 1+x (base e).
        
        The result is computed in a way which is accurate for x near zero.
    
    log2(x, /)
        Return the base 2 logarithm of x.
    
    modf(x, /)
        Return the fractional and integer parts of x.
        
        Both results carry the sign of x and are floats.
    
    perm(n, k=None, /)
        Number of ways to choose k items from n items without repetition and with order.
   
        Evaluates to n! / (n - k)! when k <= n and evaluates
        to zero when k > n.
        
        If k is not specified or is None, then k defaults to n
        and the function returns n!.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    pow(x, y, /)
        Return x**y (x to the power of y).
    
    prod(iterable, /, *, start=1)
        Calculate the product of all the elements in the input iterable.
        
        The default start value for the product is 1.
        
        When the iterable is empty, return the start value.  This function is
        intended specifically for use with numeric values and may reject
        non-numeric types.
    
 radians(x, /)
        Convert angle x from degrees to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /usr/lib/python3.8/lib-dynload/math.cpython-38-aarch64-linux-gnu.so

モジュール内のすべての関数を一度に表示できます.
3、ランダム関数はrandomをインポートする必要がある
print('return item from list:', random.choice(['spring', 'summer','autumn', 'winter']))
return item from list: autumn
>>> print('return item from list:', random.choice((27, 95, 68, 75,44)))
return item from list: 27
>>> print('return item from list:', random.choice('hello world!'))
return item from list: o
>>> print('return item from list:', random.sample(['spring', 'summer','autumn', 'winter'], 2))
return item from list: ['spring', 'summer']
>>> print('return item from list:', random.sample((27, 95, 68, 75,44),2))
return item from list: [44, 75]
>>> print('return item from list:', random.sample('hello world!', 5))
return item from list: ['r', '!', 'o', 'w', 'o']
>>> print('return item from list:', random.randint(1, 100))
return item from list: 29
>>> print('return item from list:', random.randint(50, 100))
return item from list: 55
>>> print('return item from list:', random.uniform(50, 100))
return item from list: 57.86905642417648
print('return item from list:', random.random())return item from list: 0.059261740874653634
>>> random.seed(1000)
>>> print('return item from list:', random.random())
return item from list: 0.7773566427005639
>>> random.seed('helloworld', 2)
>>> print('return item from list:', random.random())
return item from list: 0.7513369593825964

4、三角関数はmathをインポートする必要がある
>>> print('acos(0.5):', math.acos(0.5))
acos(0.5): 1.0471975511965979
>>> print('cos(math.pi/4):', math.cos(math.pi/4))
cos(math.pi/4): 0.7071067811865476
>>> print('sin(math.pi/4):', math.sin(math.pi/4))
sin(math.pi/4): 0.7071067811865475
>>> print('tan(math.pi/4):', math.tan(math.pi/4))
tan(math.pi/4): 0.9999999999999999
>>> print('atan(1):', math.atan(1))
atan(1): 0.7853981633974483

5、文字列関数をインポートする必要がある