Table of Contents
Basic overview of functions
while True:
Home Backend Development Python Tutorial Basic points in python

Basic points in python

Jul 18, 2017 pm 01:32 PM
python overall situation transfer

Basic overview of functions

Before learning functions, we have always followed: process-oriented programming, that is: implementing functions from top to bottom based on business logic. You can think about if the code for a certain function is in multiple Is it possible to write it only once if it is used in each place? How should the code be defined at this time. Observe the following case first:

while True:
if cpu utilization > 90%:
#Send email reminder
Connect to email server
Send email
Close the connection
                                                                                                                                                                                                                                                                                                   %:
#Send email reminder
Connection mailbox server
Send mail
Close connection

or above.
#def Send email (content)
#Send email reminder
Connect to email server
Send email
Close connection

while True:

if cpu Utilization rate> 90%:
Send email ('CPU alarm')

if Hard disk usage space> 90%:
Send email ('Hard disk alarm')

if Memory usage > 80%:
Send email ('Memory Alarm')

For the above two implementation methods, the second time must be better than the first time in terms of reusability and readability. It can reduce a large amount of code and development time. It can be defined in one place and called in multiple places. In fact, this is functional programming

The concept of functional programming:
When developing a program, a certain piece of code is required multiple times Use, but in order to improve writing efficiency and code reuse, code blocks with independent functions are organized into a small module. This is the function

Definition and call of the function


<1>Define function

The format of defining a function is as follows:

def function name():

Code demo: # Define a function that can complete the function of printing information
  def printInfo():
  print '---------------- --------------------------'
    print 'Life is short, I use Python'
    print '---------- --------------------------'




The definition of function mainly has the following points:


 

• def: keyword representing a function • Function name: the name of the function, the function is called according to the function name when calling

 • Function body: performed in the function A series of logical calculations or the functional content of the function.

 • Parameters: Provide data for the function body

 • Return value: After the function is executed, data can be returned to the caller.

##<2>Call the function
After defining the function, it is equivalent to having a code with certain functions. To make these codes executable, you need to call it (note that the content inside will not be executed when defining the function) Calling the function is very simple, and the call can be completed through function name ()
demo:
 #After defining the function, the function will not be executed automatically. You need to call it.printInfo()

##<3>Function Document Description

Example:

>>> def test(a,b):
... "Used to complete the sum of 2 numbers"

... print("%d"%(a+b))

...
>>> >>> test(11,22)33 Execute, the following code>>> help(test)

You can see the relevant instructions of the test function

========== ====================================

Help on function test in module __main__:

test(a, b)
Used to complete the sum of 2 numbers
(END)

=============================================

Function parameters-return value

<1> Define a function with parameters
Examples are as follows:
def addnum(a, b):
c = a+b
  print c
<2> Call a function with parameters
Take calling the add2num(a, b) function above as an example:

 def addnum(a, b):
  c = a+b
  print c

  add2num(11, 22) #When calling a function with parameters, you need to pass the data in parentheses

 Small summary:
 • Small when defining The parameters in parentheses, used to receive parameters, are called "formal parameters"
• The parameters in parentheses when called, used to pass to the function, are called "actual parameters"

ps: There will be a separate blog explaining function parameters in detail later


##<3> Functions with return values The following example:

def add2num(a, b):
c = a+b
return c 
The return value example of the saved function is as follows:
 #Define function

 
def add2num(a, b):
Return a+b

#Call the function and save the return value of the function
result = add2num(100,98)

 

 #Because result has saved the return value of add2num, you can use it next
 print result Result:
 
198


In python we can return multiple values >>> def divid(a, b):
 ... shang = a//b
 ... yushu = a%b
 ... return shang, yushu
 ...
 >>> sh, yu = divid(5, 2)
 >>> sh
 5
 >>> yu
 1

The essence is to use tuples

Functions can be combined with each other depending on whether they have parameters and whether they have a return value. There are 4 types in total
 • No parameters, no return value
 • No parameters, no return value
 • With parameters and no return value
 • With parameters and return value

 <1>Functions without parameters and no return value
  Such functions cannot be accepted Parameters and no return value. Generally, for functions similar to printing prompt lights, use this type of function
 <2>Function without parameters and return value
 This type of function cannot accept parameters, but You can return certain data. In general, like collecting data, you use this type of function
 <3>Function with parameters but no return value
 This type of function can receive parameters, but cannot return data. Under normal circumstances, when setting data for certain variables without requiring results, use such functions
 <4>Functions with parameters and return values
  Such functions can not only receive parameters, but also return A certain data, in general, like data processing and applications that require results, use this type of function

Short summary

• The function depends on whether there are parameters, whether there are Return values ​​can be combined with each other
 • When defining a function, it is designed based on actual functional requirements, so the function types written by different developers are different
 • Whether a function has a return value depends on whether there is one return, because only return can return data
• In development, functions are often designed according to needs whether they need to return a value
• There can be multiple return statements in a function, but as long as one return statement is executed, then It means that the call of this function is completed
 •
Try not to repeat the name of the function in a program. When the function name is repeated, the later one will overwrite the previous one (Note: Do not repeat the variable name, it will also be overwritten. Override)

Nesting of functions

def testB():
 print('---- testB start----')
 print('This is testB The code executed by the function...(omitted)...')
 print('---- testB end----')


def testA():

 print('---- testA start----')

 testB( )

## print('---- testA end----')

Call

testA()

Result:

---- testA start----
---- testB start----
Here is the code executed by the testB function...(omitted)...
---- testB end----
---- testA end----

Small summary •
One function calls another function, This is the so-called Function nested calling   •
If another function B is called in function A, then all the tasks in function B will be executed first before returning to the previous function. The position where secondary function A is executed

Case of function nesting:

 1. Write a function to find the sum of three numbers

 2. Write a function to find the average of three numbers


 
# Find the sum of three numbers 
def sum3Number(a,b, c):
Return a+b+c # The return can be followed by a numerical value or an expression

 

# Complete the average of 3 numbers 
def average3Number(a,b,c):

  

# Because the sum3Number function has already completed the sum of three numbers, it only needs to be called
   # That is, the three received numbers can be passed as actual parameters   
sumResult = sum3Number(a,b,c)
   aveResult = sumResult/3.0
    return aveResult

 

# Call the function to complete the average of 3 numbers

 

result = average3Number(11,2,55)

 print("average is %d"%result)

Local variables and global variables of the function

Local variables

Example:

In [8]: def text1():
...: a = 200
                                                                                                                                                                                                                                                                                       . .: ​ ​ print("text1----%d" %a)
​ ​ ​ ​ ​...:

​ ​ ​ ​ ​ ​ ​ ​ ​​ ​ ​ ​ ​ ​ ​ ​ ​ print("text1----%d" ​ ​##                                                                                                                                                                                                                                             …: # Text1----200
After modification
text1----300

In [11]: text2()
text2-----400

 

Summary

  • Local variables are variables defined inside the function

   • Different functions can define local variables with the same name, but using different ones will not have any impact
  • The role of local variables. In order to temporarily save data, variables need to be defined in the function for storage. This is its role.

Global variables


Concept: If a variable can be used in a function or in other functions, such a variable is a global variable

 

 Example:  # Define global variables  In [12]: a = 250  In [13]: def text1 ():

                                                                                                                                                            ’ ’ s ’ s ’s ’ s ’s ’ ​ ’’ ​ ’ to ​​…: ​ ” print("----text1----%d" %a)

                          …:      ;   ----text1----250

In [16]: text2()
When:

In [23]: a = 250

# Global variable In [24]: def text1(): .. .: ​ ​..: ​
​ # Local variable ​ ​ ​ ​ ...: ​ ​ ​ a = 666

​ ​ ​ ​ ...: ​ ​ ​ print("----text1----%d" %a)

...:
  In [25]: def text2():    ...:    print("----text2----%d" %a)
   .. .:

  In [26]: text1()  ----text1----521   ----text1----666

  In [ 27]: text2()
   ----text2----250

  In [28]:

 

  Summary:

  • Variables defined outside a function are called global variables

   • Global variables can be accessed in
all

functions

   • If the name of the global variable is the same as the name of the local variable, then Local variables are used, a little trick to help the powerful but not the local snake

 Modify the global variable inside the function:
In [31]: a = 250
In [32]: def text1(): ...: a = 520
print("----text1----%d" %a )

In [33]: In [33]: def text2(): ...: global
a
...: a = 666
  ...:      print("----text2----%d" %a)
                   through No function is called


In [35]: print(a)
250

In [36]: # Call text1

In [37]: text1()
----text1----520

In [38]: # Print again---->

  In [39]: print(a)
  250

  In [40]: # Found that the value has not been modified

  In [41 ]:
# Call text2

  In [42]: text2()   ----text2----666

  In [43]:
# Print a

again   In [44]: print(a)   666

  In [45]: # The value has been modified
An object of the same variable


 
The difference between a mutable type global variable and an immutable type global variable-modified inside a function


  

ps: There will be a blog later that will explain the concepts of variable types and immutable types in detail
  Example: -------> Immutable type: In [46]: a = 6
In [47]: def demo(): ...: a += 1 ...: print (a)

...:

In [48]: demo() Error message: ------------- -------------------------------------------------- -----------

   UnboundLocalError          Traceback (most recent call last)

    in ()   ----> 1 demo() # 3

   UnboundLocalError: local variable 'a' referenced before assignment

   ----------------------------- -------------------------------------------
Note:Obviously it cannot be modified

------->Variable type:

In [49]: a = [1,]

In [50]:

In [50]: def demo():
...: a.append(2)
...: print(a)
. ..:

   In [51]: demo()
   [1, 2]

   In [52]: a
   Out[52]: [1, 2]

When a function is called, the value of the list is modified inside the function when the function is executed - and also changed when printed externally.
Summary:

  ○ If you modify a global variable in a function, you need to use global for declaration, otherwise an error will occur
  ○ Do not use global declaration in a function The essence of global variables that cannot be modified is that cannot modify the point of global variables, that is, cannot point global variables to new data. ○ ○ For global variables of
immutable type , the data pointed to by cannot be modified , so if global is not used, cannot modify the global variable.  ○ For global variables of
variable type, the data they point tocan be modified, so global can also be modified when global is not used variable.

The above is the detailed content of Basic points in python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the &lt;width&gt; and &lt;height&gt; tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

What is the process of converting XML into images? What is the process of converting XML into images? Apr 02, 2025 pm 08:24 PM

To convert XML images, you need to determine the XML data structure first, then select a suitable graphical library (such as Python's matplotlib) and method, select a visualization strategy based on the data structure, consider the data volume and image format, perform batch processing or use efficient libraries, and finally save it as PNG, JPEG, or SVG according to the needs.

See all articles