picture

First, the basic steps of Python custom function


1. What is a function



Functions, in fact, we came into contact with them when we first learned Python.
But most of what we use are built-in functions of Python.
print()  For example, functions that appear in basically every chapter .
For now, we are mainly learning about custom functions.
Have you ever wondered why you need functions?
To answer this question, we need to understand what a function is?
A function is an organized, reusable piece of code that implements a single, or related function.
Yes, functions are actually code segments that abstract code.
So why abstract it?
It is convenient for us to use and convenient for us to reuse.
The essence of the function is that we feed some data to the function, let it digest internally, and then spit out what you want. As for how it digests, we don’t need to know, it resolves internally.
How to understand this sentence?
For example, every time we use the print function, we know that the function of this function is to output our data to the console for us to see. So print('两点水'), if we want to print 两点水it , we 两点水feed this data to the   printfunction, and it prints the result directly to the console.

2. How to customize the function


How to customize the function?

To know how to define a function, you need to know what the components of a function look like.

def 函数名(参数1,参数2....参数n):    函数体    return 语句

That's what a Python function is all about.
So the custom function basically has the following rule steps:
  • A block of function code begins with the def keyword, followed by the function identifier name and parentheses ()

  • Any incoming parameters and arguments must be enclosed in parentheses. between parentheses can be used to define parameters

  • The first line of the function can optionally use a docstring (for function description)

  • Function content starts with a colon and is indented

  • return [expression] Ends a function, optionally returning a value to the caller. return without an expression is equivalent to returning None.

Syntax example:
def functionname( parameters ):   "函数_文档字符串"   function_suite   return [expression]

Example:
  1. def defines a function, given a function name sum

  2. declare two parameters num1 and num2

  3. The first line of the function statement describes the function: the sum of two numbers

  4. The final return statement ends the function and returns the sum of the two numbers

def sum(num1,num2):  "两数之和"  return num1+num2
# 调用函数print(sum(5,6))

Output result:

11

Featured Article Recommendations





Follow me and catch the latest and most trendy black technology together