Use of lightweight Python IDE (3) - Function

1. Function

1.1. Overview of functions

In programming, the use of functions can improve code reusability and maintainability.

The system's built-in function pow() performs exponentiation operations:

a = pow(2,4)

Custom function func()

def func(a,b):
    return a ** b
a=func(2,4)
print(a)

Custom function func(), the function is to output the b power of a

1.2. Definition of function

In the Python language, a function is usually composed of a function name, a parameter list, and a function body composed of a series of statements. The function definition is generally as follows

def 函数名(参数列表)
    函数体

example:

def foo():
    print("I am")
    print("foo")

Although the first foo() function above does not contain any parameters, the pair of parentheses after the function name cannot be omitted. In practical applications, slightly more complex functions usually contain one or more parameters.

def area(width,height):
    return width * height
#调用area
w = 7
h = 9
print("width=",w,"height=",h,"area=",area(w,h))

The following defines an empty function none() that does no operation

def none():
    pass

In Python, the pass statement can usually be used as a placeholder to indicate that no operation will be performed. For example, at the beginning of the project, if you have not thought about the specific implementation of the function, you can first place a pass statement to let the code run successfully first. After the project framework is completed, the corresponding specific implementation will be carried out.

Normally, defining a function with specific functionality in the Python language requires the following rules:

  • The function code block starts with the def keyword, followed by the function identifier name and formal parameter list;
  • Any parameters and arguments passed in must be enclosed in parentheses;
  • The first line of a function statement can optionally use a docstring;
  • Function content starts with a colon and is strictly indented;
  • All functions have a return value, and None is returned by default.

1.3. Formal parameters and actual parameters

In programming languages, when a function is defined with formal parameters, what is called is the actual parameters.
Formal parameter (parameter), the full name is "formal parameter", is not an actual variable. Also called dummy variable. Used to receive the parameters passed in when calling this function.

Actual parameter (argument), the full name is "actual parameter", is the parameter passed to the function when calling. Actual parameters can be constants, variables, expressions, functions, etc.

def area(width,height):
    return width * height
#调用area
w = 7
h = 9
print("width=",w,"height=",h,"area=",area(w,h))
其中w=7,h=9中的w,h是实参,area(w,h))中的w,h是形参

It can be seen that the actual parameters are passed into the function parameter position, and the value of the actual parameters will not be affected after the call is completed.

a = 1
b = 2

def func(x,y):
    x+=1
    y+=2
    print(x)#2
    print(y)#4
func(a,b)
print(a)#1
print(b)#2

func(a,b), etc. func(1,2), func(x=1,y=2), func(y=2,x=1)

1.4. Return value of function

In Python, when the function reaches the return statement, it is executed and the result is returned. Therefore, more complex logic can be implemented inside the function through conditional judgment and loop settings, and the expected results can be returned. If there is no return statement, None will be returned by default after all statements in the function body are executed.

def add(x,y):
    print('x+y=',x+y)
    return x+y
result = add(y=1,x=2)
print(result)

Functions can also have multiple return values

def add(x,y):
    print('x+y=',x+y)
    print('x*y=',x*y)
    return x+y,x*y
a,b = add(y=1,x=2)
print(a,b)

Note that the relationship between the return value and the receiving variable is one-to-one.

2. Function classification

2.1 Built-in functions

The functions that come with the Python language are called built-in functions. These built-in functions effectively encapsulate most common operations and can be called directly, which provides great convenience for development. Since built-in functions are functions built into the Python language, they can be called directly without importing any function library. Commonly used built-in functions are as follows:

  1. abs(x): Returns the absolute value of x.

  2. all(iterable): If all elements of iterable are True, return True; otherwise, return False.

  3. any(iterable): If any element of iterable is True, return True; otherwise, return False.

  4. ascii(obj): Returns a printable string representation of the object.

  5. bin(x): Converts the integer x to a binary string.

  6. bool(x): Convert x to a Boolean value. Converts to False if x is False, 0, empty list, empty dictionary, and empty string; otherwise, converts to True.

  7. bytearray(iterable): Returns a byte array composed of the elements in the iterable object iterable.

  8. bytes(iterable): Returns a bytes object composed of elements in the iterable object iterable.

  9. callable(obj): If obj is callable (such as function, method, class), it returns True; otherwise it returns False.

  10. chr(i): Returns the character whose Unicode value is i.

  11. classmethod(func): Convert function func into a class method.

  12. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1): Compile source into a code object or AST object. Can be used to dynamically execute code.

  13. complex(real, imag): Create a complex number, where real is the real part and imag is the imaginary part.

  14. delattr(obj, name): Delete the attribute named name from object obj.

  15. dict(): Create an empty dictionary.

  16. dir(obj): Returns a list containing the names of all properties and methods defined by object obj.

  17. divmod(a, b): Returns a tuple of the quotient and remainder of a divided by b.

  18. enumerate(iterable, start=0): Returns an enumeration object containing each element in iterable and its corresponding index.

  19. eval(expression, globals=None, locals=None): Execute the string expression as Python code and return the result.

  20. exec(obj[, globals[, locals]]): Execute object obj (can be a string or code object) as Python code.

  21. filter(function, iterable): Returns an iterator consisting of elements in iterable that satisfy the function.

  22. float(x): Convert x to a floating point number.

  23. format(value[, format_spec]): Convert value into a string according to the format of format_spec.

  24. frozenset(iterable): Create an immutable set.

  25. getattr(obj, name[, default]): Returns the value of the attribute named name of object obj.

  26. globals(): Returns the dictionary of the current global symbol table.

  27. hasattr(obj, name): Returns True if the object obj has an attribute named name; otherwise returns False.

  28. hash(obj): Returns the hash value of object obj.

  29. help(obj): Provides help information for object obj.

  30. hex(x): Convert the integer x to a hexadecimal string.

  31. id(obj): Returns the unique identifier of object obj.

  32. input([prompt]): Read a line of string from standard input.

  33. int(x[, base]): Convert x to an integer. If base is provided, treats x as a string in base base, converting it to decimal.

  34. isinstance(obj, classinfo): Returns True if the object obj is an instance of classinfo or an instance of a derived class; otherwise, returns False.

  35. issubclass(class, classinfo): Returns True if class is a derived class of classinfo; otherwise, returns False.

  36. iter(obj[, sentinel]): Returns an iterator object.

  37. len(obj): Returns the length (number of elements) of object obj.

  38. list(iterable): Convert the iterable object iterable to a list.

  39. locals(): Returns the dictionary of the current local symbol table.

  40. map(function, iterable): Apply function to each element in iterable and return an iterator containing the results.

  41. max(iterable[, key]): Returns the largest element in iterable. Comparison rules can be specified using the key function.

  42. memoryview(obj): Returns the memory view of object obj, which can be used to perform native memory operations on the object.

  43. min(iterable[, key]): Returns the smallest element in iterable. Comparison rules can be specified using the key function.

  44. next(iterator[, default]): Returns the next element of the iterator iterator. If the end of the iterator has been reached, default is returned.

  45. object(): Returns a new object without any special behavior.

  46. oct(x): Convert the integer x to an octal string.

  47. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): Open the file and return the file object.

  48. ord©: Returns the Unicode value of character c.

  49. pow(x, y[, z]): Returns x raised to the power of y. If the parameter z is provided, the modulus of the calculation result is z.

  50. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False): Print objects to a stream file, the default is standard output.

  51. property(fget=None, fset=None, fdel=None, doc=None): Create a property, where fget, fset and fdel are methods for getting, setting and deleting property values.

  52. range(stop): Returns a sequence of integers from 0 to stop-1.

  53. repr(obj): Returns the string representation of object obj.

  54. reversed(seq): Returns a reversed iterator for iterating over the elements of sequence seq.

  55. round(number[, ndigits]): Returns the rounded value of a floating point number.

  56. set(iterable): Creates a set containing the elements in iterable.

  57. setattr(obj, name, value): Set the attribute name of object obj to value.

  58. slice(stop): Create a slice object for cutting elements from 0 to stop-1.

  59. sorted(iterable[, key[, reverse]]): Returns a sorted copy of iterable.

  60. staticmethod(func): Convert function func into a static method.

  61. str(obj): Convert object obj to string.

  62. sum(iterable[, start]): Returns the summation result of iterable.

  63. super([type[, object-or-type]]): Returns a chained object for calling parent class methods in multiple inheritance.

  64. tuple(iterable): Convert the iterable object iterable to a tuple.

  65. type(obj): Returns the type of object obj.

  66. vars([object]): Returns the __dict__ attribute of the object object, or returns the dictionary of the current local symbol table.

  67. zip(*iterables): takes multiple iterators as parameters and combines elements at corresponding positions into tuples.

  68. 1__import__ (name[, globals[, locals[, fromlist[, level]]]]): Use the import mechanism to import a module.

  69. openpyxl(): Library for manipulating Excel files.

In the Python language, other types of functions besides built-in functions are usually called third-party functions.

a = abs(-100)
b = max(-1,4,0,-2,13,4)
print(a,b)#100 13

Commonly used built-in functions in the Python language also include data type conversion functions.

print("int('12'):",int('12'))
print("int(12.5):",int(12.5))
print("float('12.5'):",float('12.5'))
print("str(1.25):",str(1.25))
print("str(10):",str(10))
print("bool(1):",bool(1))#True
print("bool(''):",bool(''))#False

In the Python language, you can also assign a function name to a variable, which is equivalent to giving the function an alias.

a = abs
print(a(-1))

2.2 Custom functions

When built-in functions cannot meet the requirements, developers can customize functions according to actual needs. After the function is customized, developers can call it through the function name in other codes.

def printme(str):
    "函数功能:打印传入的字符串"
    print(str)

printme("调用自定义函数")

In the Python language, built-in functions can be used directly, while third-party functions need to use the import command to import the corresponding library before they can be used. For custom functions, their definition and calling can be in one file or separated into different files.
Define a func.py and write the hello function

def hello():
    print("你好")

Call hello in a new xx.py file

from func import hello
hello()

3. Function parameters

3.1 Parameter types

Function parameters are divided into variable types and immutable types, and their calling results are different.

  • Variable types: similar to C++ reference passing. Such as lists, dictionaries, etc. If the passed parameters are of variable type, modifications to the passed parameters inside the function will affect external variables.
  • Immutable types: C++-like value transfer, such as integers, strings, tuples, etc. If the passed parameters are immutable types, modifications to the passed parameters inside the function will not affect external variables.

Immutable type parameters, for example:

def change_int(a):
    a=10
b=2
change_int(b)
print(b)#结果是2

The value of b remains unchanged
as a variable type parameter, for example:

def change_int(my_list):
    my_list.append([1,2,3])
    print("函数内修改后的变量:", my_list)#[10, 20, 30, [1, 2, 3]]

my_list =[10,20,30]
change_int(my_list)
print("函数外变量的值:", my_list)#[10, 20, 30, [1, 2, 3]]

The value of my_list changes

3.2 Position parameters

When calling a function, the Python language must associate each actual parameter in the function call to the corresponding formal parameter of the function. The simplest association is based on the order of the arguments, which are called positional arguments.

def student_info(name,age):
    print("my name is",name ,age," years old")

student_info('jack',24)

output

my name is jack 24  years old

3.3 Default parameters

When writing a function, you can specify a default value for each formal parameter. Note that the required parameters come first and the default parameters come last.
Example of the following error

def student_info(name='liuj',age):
    print("my name is",name ,age," years old")

Correct operation

def student_info(name,age=24):
    print("my name is",name ,age," years old")

student_info('jack')

3.4 Indefinite length parameters

Developers can pass in a list or tuple

def sum(numbers):
    i=0
    for n in numbers:
        i = i + n
    return i
print(sum([1,2,3]))#6
print(sum([1,2,3,4]))#10

You can also add a * sign in front of the function parameter to define the parameter as a variable length parameter.

def sum(*numbers):
    i=0
    for n in numbers:
        i = i + n
    return i
print(sum())#0
print(sum(1,2,3,4))#10
num = [1,2,3]
print(sum(*num))#6

3.5 Keyword parameters

Keyword arguments use "name-value" pairs when passing parameters, and associate names and values ​​in the arguments. There is no need to consider the order of arguments in the function call.

def func(a,b):
    return pow(a,b)
print(func(b=4,a=3))#81

3.6 Named keyword parameters

If you want to limit the names of keyword arguments, you can use named keyword arguments. Unlike the keyword parameter **kw, if there are no variable parameters, the named parameter keyword parameter must be added with an * sign as a special separator. If * is missing, the Python language interpreter will not recognize positional parameters and named keyword parameters.

For example, if you only receive age and city as keyword parameters, you can use the following form.

def person_info(name,denger,*,age,city):
    print(name,denger,age,city)

person_info('jack','M',age=18,city='guangzhou')

Note that
* indicates variable-length parameters
** indicates variable-length keyword parameters

3.7 Parameter combination

When defining functions in the Python language, developers can use a combination of these parameters (required parameters, default parameters, variable parameters, keyword parameters and named keyword parameters). Note that parameter definitions are in order. The definition order must be: required parameters, default parameters, variable parameters, named keyword parameters, keyword parameters.

def func(a,b,c=0,*args,**kw):
    print(a,b,c,args,kw)

func(1,2,3,'a','b',x=4,y=7,z=8)

operation result:

1 2 3 ('a', 'b') {
    
    'x': 4, 'y': 7, 'z': 8}

4. Functional programming

  • Functional programming is a programming paradigm, a mathematically oriented abstraction that describes computation as an expression evaluation.
  • The function in functional programming does not refer to the function of the computer, but to the function in mathematics, that is, the mapping of independent variables.
  • One feature of functional programming is that it allows a function itself to be passed as a parameter to another function, and it also allows a function to be returned.

4.1. Higher-order functions

Functions that accept functions as parameters or return functions as results are called higher-order functions.

word = ['apple','blue','car','did']
def reverse(word):
    return word[::-1]
    
print(sorted(word,key=len))

print(reverse('testing'))

print(sorted(word,key=reverse))

4.2. Anonymous functions

The so-called anonymous function is a function that is no longer defined in a standard form such as a def statement. Python often uses lambda to create anonymous functions.
lambda arg1,arg2…:expression

sum = lambda arg1,arg2:arg1+arg2
print(sum(2,3))

Guess you like

Origin blog.csdn.net/weixin_45724919/article/details/135159088