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

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view server version of Redis How to view server version of Redis Apr 10, 2025 pm 01:27 PM

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to set the Redis memory size according to business needs? How to set the Redis memory size according to business needs? Apr 10, 2025 pm 02:18 PM

Redis memory size setting needs to consider the following factors: data volume and growth trend: Estimate the size and growth rate of stored data. Data type: Different types (such as lists, hashes) occupy different memory. Caching policy: Full cache, partial cache, and phasing policies affect memory usage. Business Peak: Leave enough memory to deal with traffic peaks.

What is the impact of Redis persistence on memory? What is the impact of Redis persistence on memory? Apr 10, 2025 pm 02:15 PM

Redis persistence will take up extra memory, RDB temporarily increases memory usage when generating snapshots, and AOF continues to take up memory when appending logs. Influencing factors include data volume, persistence policy and Redis configuration. To mitigate the impact, you can reasonably configure RDB snapshot policies, optimize AOF configuration, upgrade hardware and monitor memory usage. Furthermore, it is crucial to find a balance between performance and data security.

Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

See all articles