Python Learning Path 4

Source: Internet
Author: User
Tags define local square root variable scope

One, character encoding and transcoding

1. In Python2 the default encoding is ASCII, python3 default is Utf-8

2.unicode is divided into utf-32 (4 bytes), utf-16 (accounting for two bytes), Utf-8 (1-4 bytes), so utf-16 is now the most commonly used Unicode version, but in the file is still utf-8, because the UTF8 save space

3. Encode in Py3, while transcoding will also change the string to bytes type, decode decoding will also turn bytes back to string

In Python3
#-*-coding:gb2312-*-#这个也可以去掉__author__='XXX'ImportSYSPrint(sys.getdefaultencoding ()) MSG="Mbappe"#msg_gb2312 = Msg.decode ("Utf-8"). Encode ("gb2312")msg_gb2312 = Msg.encode ("gb2312")#The default is Unicode, no longer decode, hi Big Ben, if it is py2 need to decode into Unicode and then encoded into gb2312Gb2312_to_unicode = Msg_gb2312.decode ("gb2312") Gb2312_to_utf8= Msg_gb2312.decode ("gb2312"). Encode ("Utf-8")Print(msg)Print(msg_gb2312)Print(Gb2312_to_unicode)Print(Gb2312_to_utf8)

Second, function

The term function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, and the function in programming has many different names in English. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

  Features: 1, reduce duplicate code

2, enhance the process of expansion

3. Improve program maintainability

def Sayhi ():# function name    print("Hello, I ' m xxx! "  # Call function

  function parameters

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

# The following code , a b =5,8 = a**bprint(c  )# changed to write Def with a function  Calc (x, y):  #xy is    parameter res =x**    yreturn# returns the function execution result  = Calc (b) # result assigned to c variable (AB is argument)print(c)

  Default parameters  

defStu_register (name,age,course,country="CN"):      Print("----Registered Student information------")      Print("Name:", name)Print("Age :", age)Print("Nationality:", Country)Print("Course:", course)
Stu_register ("XXX", 18,"Music")

If country does not specify the default is CN, the specified value is the one you specified.

   Key Parameters

Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, But remember a requirement is that the key parameters must be placed after the position parameter.

Stu_register (age=18,name='xzx', course="music",)

  Non-fixed parameters

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

defStu_register (Name,age,*args):#*args will change multiple incoming parameters into a tuple form.    Print(Name,age,args) stu_register ("XXX", 18)#Output#xxx () #后面这个 () is args, just because there is no value, so it is emptyStu_register ("Messi", 31,"ARG","Football")#Output#Messi (' ARG ', ' Football ')

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 within subroutines that define local variables, and global variables work in other places. Local Variables  
" XXX " def change_name (name):     Print ("before change:", name)     " Zed "    Print ("after change", name)   Print (" global ", name)

Output

Before change:xxxafter change Zed global xxx inside the function, you can call other functions. If a function calls itself internally, the function is a recursive function.

return value

To get the result of the function execution, you can return the result using the return statement

Note: 1. The function will stop executing and return the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function.

2. If return is not specified in the function, the return value of this function is None

 Recursive

  Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

def Calc (n):     Print (n)     if int (N/2) = =0        :return  n    return calc (int (n/2)) Calc (10521) output:

Recursive properties:

1. Must have a definite end condition

2, each time into a deeper level of recursion, the problem size should be reduced compared to the last recursion

3., recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

III. Introduction to Functional programming

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.

Functions in functional programming the term does not refer to a function in a computer (actually a subroutine), but rather to a function in mathematics, the mapping of an independent variable. This means that the value of a function is determined only by the value of the function parameter, not by other states. For example, the sqrt (x) function calculates the square root of X, as long as x is not changed, and whenever the call is called, the value is constant.

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

First, the definition

Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.

The main idea is to write the operation process as much as possible into a series of nested function calls. For example, there is now a mathematical expression:

(1 + 2) * 3-4

Traditional procedural programming, which may be written like this:

var a = 1 + 2;

var B = A * 3;

var c = b-4;

Functional programming requires the use of functions, which can be defined as different functions, and then written as follows:

var result = Subtract (multiply (add), 3), 4);

This code evolves the following and can be turned into this

Add. Multiply (3). Subtract (4)

This is basically the expression of natural language. Look at the following code, you should be able to understand its meaning at a glance:

Merge ([1,2],[3,4]). Sort (). Search ("2")

As a result, the code for functional programming is easier to understand.

Higher order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

def Add (x,y,f):     return f (x) + f (y)  = Add (3,-6, ABS)print(res)

Python Learning Path 4

Related Article

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.