python function basics

python function

  • Basic Definition of Function
  • function parameter
  • return value
  • local and global variables
  • nested functions
  • anonymous function
  • Higher order functions
  • recursion

Basic Definition of Function

Introduction

Now your boss asks you to write a monitoring program to monitor the running status of your company's website server 24 hours a day, and send an alarm email when the usage of cpu\memory\disk and other indicators exceeds the threshold:

while True:
    if cpu利用率 > 90%:
        #发送邮件提醒
        连接邮箱服务器
        发送邮件
        关闭连接

    if 硬盘使用空间 > 90%:
        #发送邮件提醒
        连接邮箱服务器
        发送邮件
        关闭连接

    if 内存占用 > 80%:
        #发送邮件提醒
        连接邮箱服务器
        发送邮件
        关闭连接

Then when your colleague sees this code, they will find that the code is relatively repetitive. Every time an alarm is issued, a piece of code for sending emails must be rewritten. The constant copy and paste does not meet the temperament of high-end programmers at all. , Secondly, if you want to modify the code for sending emails in the future, such as adding a group sending function, then you need to modify all the codes again.

You can also see this problem, you don't want to write repeated code, but you don't know how to write it. At this time, you smiled and said to you, this is very simple, just put the repeated code out and put it in a public place, give a name, and whoever wants to use this code in the future can call it through this name. , as follows:

def 发送邮件(内容):
    # 发送邮件提醒
    连接邮件服务器
    发送邮件
    关闭连接

while True:
    if cpu利用率 > 90%:
        发送邮件('CPU报警')
    if 硬盘使用空间 > 90%:
        发送邮件('硬盘报警')
    if 内存占用 > 80%:
        发送邮件('内存报警')

basic definition

What is a function?

The word function comes from mathematics, but the concept of "function" in programming is very different from the function in mathematics. Functions in programming also have many different names in English. In BASIC it is called subroutine (subprocess or subprogram), in Pascal it is called procedure (process) and function, in C there is only function, in Java it is called method.

Definition: A function refers to encapsulating a set of statements with a name (function name). To execute this function, you only need to call its function name.

Features of the function

  • reduce duplicate code
  • make the program extensible
  • make the program maintainable

Grammar definition

def sayhi():  # sayhi函数名
    print('hello world')

sayhi()  # 调用函数

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325219802&siteId=291194637