python learning, function

python functions

A function is a block of code with a certain functional aggregation

1
2
3
4
5
def get_name(name):
  "" "
    Get name
  "" "
  return 'Hello front club, %s'% name

Function declaration

Referring to the above, several rules for defining functions

  • The keyword def stands for function definition
  • Followed by the function name, the naming rules of the function names are the same as the previous variable name naming rules (see naming rules)
  • The parameter list is in parentheses, even without parameters
  • After the colon: the function body is followed by the indentation.
  • Functions generally return the function return value through return
  • Three quotes on the first line of the function body. The document string is usually used to describe the function.

Let’s look at a few more examples:

1
2
3
4
5
6
7
8
def sum():
  pass

def get_sum(a, b):
  return a + b

print(sum())
print(get_sum(1, 3))

Save as helloworld.py and execute the result

1
2
3
[me@VM_0_14_centos python] # python helloworld.py
None
4

Lines 1 to 2 define the function sum, and the function body is pass, that is, no statement is executed
Lines 4 to 5 define the function get_sum, which takes two parameters a and b, and returns the sum of a and b
Line 7 prints the return value of the sum function. Since there is no return value, it is None.
On line 9, get_sum (1, 3) is the function call, passing two parameters 1 and 3

Function call

The function call format is function name + parentheses:
Function name (parameter 1, parameter 2, …)

Default function

1
2
3
4
5
6
def get_sum(a, b = 4):
  return a + b

print(get_sum(1))

print(get_sum(1, 9))

Save as helloworld.py and execute the result

1
2
3
[me@VM_0_14_centos python] # python helloworld.py
5
10

From the execution results:
Line 4, the function call, only 1 parameter is passed, but the returned value is 5, because b uses the default value
Line 6 is also a function call, passing 2 parameters, without using the default parameters, all return values ​​1 + 9 equal to 10

Persist in original technology sharing, your support will encourage me to continue to create!