Python character encoding and function basic use-DAY3

Source: Internet
Author: User
Tags define local types of functions variable scope

    • Solve the problem of character encoding in Python2 and Python3
    • Description of the file operation in the supplemental Python2
    • Function Usage Basics
    • Types of functions

The problem of decoding encoding in the presence of characters in Python2

If you are now using Python2 people should know that there is a character encoding problem, to give a simple example: Python2 is not able to print in the command line of Chinese, of course, he will not error, at most, is a bunch of garbled you can not understand. If you want to display the Chinese directly, we can declare the character encoding format in the Python2 file header. Such as

Here #-*-coding:utf-8-*- is used to affirm what code is used to interpret the following codes;

Decoding and encoding in the 1.1.python2:

In the world of coding and decoding, we need to find a word that everyone knows. Can also be understood as such. I am a Chinese now and a Japanese communication, I certainly do not understand what he said, he also can not understand, but there is no way to do it? Perhaps we need an international language-English. So people from different countries can also communicate (although I know is you OK 0-0). In the code is the same, GBK and utf-8 do not know the other side of the format is what hanging meaning. So if you want to read Utf-8 code on the GBK to Utf-8 decode into Unicode, and Unicode has to know gkb, where the Unicode in encode to GBK on the line

# -*-coding:utf-8-*-  " China "print  msg# decoding in the process of encoding, Encoding is a statement of what this code is encoded GBK_STR = Msg.decode (encoding='utf-8'). Encode ( encoding='gbk')print  gbk_str#  Actually, the results are the same for both types of output .

In Python2, the default is to use GBK to interpret the code in the IDE, so you cannot directly enter Chinese directly on the Python command line, so we will use #-*-coding:utf-8-*-to declare the head, exactly what language we need to use to interpret the code below. Careful people must have found a problem, stating that the head is only using Utf-8 to explain the following, it is supposed to be the command line although not an error, but it should also be garbled is, here is why the direct output of Chinese it is the DOS command line default support is the GBK format of the character code ah? Here comes another concept. Python into the memory interpreter, the default is the Unicode, the file is loaded into memory automatically decoded into Unicode, and Unicode is a foreign code, it is natural to translate the code from Utf-8, can also be translated into GBK encoding. Gu can display the Chinese.

PS: Here we come to the conclusion that thedecoding action in Python2 is necessary, but the encoding can be used, because memory is Unicode

1.2, the problem of character encoding in Python3:

Well, what else can we say? Python3 default is to use Utf-8 to interpret the code. That is, the beginning of the line with #-*-coding:utf-8-*-(GBM), so there is no decoding problem. But I put a mouth here (in fact, I am afraid of myself later also forget, hey), if we will utf-8 character encoding format to encode into GBK. This will output something in the bytes format.

What the hell is bytes? Here I simply say. This is actually the corresponding position of this character in ASCII code. Do not believe, we look through a code:

In this picture, we see that China has been sent into a bunch of ignorant birds. And the English is still showing. But we through the interception of the list, we can see that the last one of the C output is 99, in fact, this output is the ASCII c corresponding to the location, and 3 bytes is a Chinese, so we see 6 paragraphs of bird text, here we do not explain too much.

PS: We have to remember a thing is:Python2 inside the STR is Python3 in the bytes format, and Python2 str is actually Unicode

Second, Python3 to file Operation supplement

2.1. File operation with "+":

Here I will say three, but actually these things are not any bird use, but this is counted on a knowledge point

r+: Readable, can be added
w+: Empty the source file and write new content
A +: Append, can read

  

f = open ('lyrics','r+', encoding='utf-8 ' # Here's lyrics is the file name f.read ()   #f.write ("Leon has Dream ")    # Append F.close () in the back

r+: If first f.read () and then F.write () is appended at the end of the file, if it is directly f.write () the contents of the beginning of the file will be replaced directly ();

f = open ('lyricsback','w+', encoding='utf-8  ') f.read () f.write("Leon has Dream") f.read () f.close ()

w+: In fact, the content is emptied and then re-written to the write (), and F.read () will not error, personal advice can be done at the time of departure to do this operation

f = open ('lyricsback','a+', encoding='utf-8  ') f.read () f.write("Leon has A draem") F.read () F.close ()

A +: In fact, very similar to r+ is the addition of content in the end, readable content

PS: Here's a supplement, Why do F.read () and then execute F.write () when using r+, and then append to the end of the file and directly use F.write () to replace the front of the file directly? This is because Python maintains this "pointer" while reading the file, and if we use F.read () is equivalent to reading the file, then the pointer will be at the end. I'm going to add a few usages of the object "F" to prove the Python file pointer.

f = open ('Lyricsback','r+', encoding='Utf-8')Print(F.tell ())#This number is 0F.seek (12)#move the pointer back a few bytes, a Chinese character is three bytesPrint(F.tell ())#This is seek numberF.write ("Love Girl")#here, from seek to local replacement .Print(F.tell ())#the Tell () usage is the pointer position of the fileF.close ()

2.2, plus B the way to operate the file

RB: Read the file in binary form from the hard drive, and remember not to add encoding= to the open () function because the binary does not have an encoding problem

WB: Writes the file as binary, but adds encode= "Utf-8" to the F.write (), meaning that the encoded format is declared and the original file content is clear

AB: can only be appended in binary mode.

Third, function

What is a function? A function can simply understand a set of commands. Why do I need to use a function? Here is a very simple reason, for example, you need to work on a piece of code repeatedly, here you can of course copy and paste, but this flexibility and future maintenance costs will become larger.

 #   Let's say that you need to write an alarm (calling interface) program, and here's a metaphor for monitoring.  Span style= "COLOR: #0000ff" >if  CPU > 80%: Connect a mailbox server send a message close connection  if  memery > 80%: Connect mailbox server Send message close connection  if  disk > 80% Connect mailbox server send message close connection  #   by writing such a program we find that we have been repeatedly invoking this set of interfaces for sending mailboxes. So can we come up with a way to solve such repetitive operations? See next version   send mail (): L Connect Mailbox Server send connection close connection  if CPU > 80% send mail ()  if  memery > 80%: Send mail () ...  #   and so on and so on, we just need to pick this interface to send messages to save the code from sending a message  

Through the above code we find that we just need to put the alarm of this set of procedures in a common place, and so on the following trigger the conditions of the alarm call function, so we can save when the alarm every time we write the alarm step. But how does a function define it? What grammar and definition do you have? Take a look at the following piece of code, where the code output is "Leon has A Dream"

def Leon ():  #Leon is the function name    print("Leon has A Dream" # call function  

Functions with Parameters:

A = ten= 5def  Calc (A, b      ):print(A * * = Calc (A, b) Print (c)

First of all, the above code will output two characters, one is 10000, one is none, why is this? First C is equal to executing the CALC function again, so the output 10000 is positive, but why does it output a none? Originally our "C" executed the Instrument Calc function, and the CALC function did not have any return value, so c = = None.

PS: The return of the function returns, where return means to return the result of the execution of the function to the outside, so that the "object" of the function is selected to get the result of the execution.

  

Now we're looking at a similar analogy.

A = ten= 5def  Calc (A, b    ):Print(A * *    )return A +  == Calc (10,6)print(c)

First will output has three values, respectively is 100000,1000000,16, why is this three, below with a picture to say

Ps:

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

Global variables and local variables in Python

PS: Inside the function is can modify the list, dictionary, collection, instance (class), we use the following diagram to illustrate

  Why lists and dictionaries are added and modified, the original function internal knowledge refers to the dictionary and the memory address of the list, and the memory address cannot be modified (can re-open a memory address), and each dictionary and list each value has a corresponding memory address, But remember that our function is a reference to the list or the memory address of the dictionary itself, so the print to come out will then change.

Global vs. local variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.
The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable.
When a global variable has the same name as a local variable:
Local variables work in sub-programs that define local variables, and global variables work elsewhere.

Position parameters:

As above, the argument and parameter one by one correspond to the positional parameters.

Default parameters:

The variable that sets a positional parameter to a default value in the function is the default parameter, remembering that the default parameter has to be followed by the positional argument

Key parameters:

As above, the argument and the parameter do not correspond, and when the function is called the parameters are called the key parameter

Non-stationary functions:

By outputting the results we find that *args is the parameter that receives the extra string type, and the python= "Simple" (dictionary) type is passed to **kwargs, which is a non-fixed parameter; You can use this function type when you don't know how many arguments this parameter requires

Recursive function--two-point lookup

A = [1,2,3,4,5,7,9,10,11,12,14,15,16,17,19,21]defCalc (num,find_num):Print(num) Mid= Int (len (num)/2)    ifMID = =0:ifNum[mid] = =Find_num:Print("Find it%s"%find_num)Else:            Print("cannt Find Num")    ifNum[mid] = =Find_num:Print("Find_num%s"%find_num)elifNum[mid] >Find_num:calc (num[0:mid],find_num)elifNum[mid] <Find_num:calc (Num[mid+1:],find_num) Calc (A,12)

Characteristics of recursion

    1. The function must have a definite end (judging) condition, that is, the first mid[0] cannot be equal to 0, because it is meaningless.
    2. Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
    3. Recursive functions each down recursively, the last memory address used by the function will not be freed, but will always be blocked by the main, waiting for the function to be released after all execution, so it can be said that recursion is quite a memory space, the python has recursive depth, if more than the depth function will be rolled out (stack overflow)

Anonymous functions:

Calc =LambdaX:x+2 # x is a formal parameter, and the content after the colon is the action performed by the anonymous functionPrint(Calc (5)) #匿名函数意识需要通过调用来执行的calc=Lambdax,y,z:x*y*z #匿名函数可以传入多个形参, separate each parameter with a commaPrint(Calc (2,4,6)) C= Map (Lambdax:x*2,[2,5,4,6]) forIinchC:Print. IO#Ternary Operations forIinchMapLambdaX:x**2ifX >5Elsex-1,[1,2,3,5,7,8,9]): #lambda最多支持三元运算, Map calls anonymous functions directly, but if you want to print the contents of a map, you need to loopPrint(i)

Higher order functions:

def Calc (x,y,f):     Print (f (x) + f (y)) calc (10,-10,abs)

Characteristics of higher order functions

    1. Pass the memory address of a function to another function as a parameter
    2. A function returns the return value of another function

Satisfying one of the two attributes above can be called a higher-order function, where lazy is the direct invocation of the built-in function in Python.

To here can be said that the third day of the notes have been written, which I think the later use more is higher-order functions, including the next note will appear in the nested function, anonymous functions and recursive functions relatively less, because one is to compare the consumption of memory system, the other is not used.

Python character encoding and function basic use-DAY3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.