Learn Python Basics---3.1

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

The programming method is about three kinds of

1. Object-oriented

2. Process oriented

3. Functional programming

These three kinds of programming methods have their own characteristics

Object-Oriented classes class

Process-oriented Def

Function-type programming function score

Definition of the function:

Definition of mathematical function: Generally, in a process of change, if there are two variables x and y, and for x is a definite value, Y has a unique value corresponding to, then we call X as the argument, Y is the function of X. The range of values of the argument x is called the definition field of the function.

Programming language definition: A programming method of functional logical structure and process

# methods for defining functions in Python def Test (x):      " " The function Definitions " "     x+=1    return x # def: A keyword that defines a function # test: Name of function # "": File Description # x+=1: Processing logic for code or programs # Return : Define the return value

Functional programming: First define a number function and then follow this mathematical model to implement it in a programming language

Procedure is a function with no return value

In the PY process is implicitly returned to none, and is also treated as a function

#functiondeffunc1 ():" "Testing" "    Print('In the funcl')    return0#procedure does not return a value for a functiondefFunc2 ():" "Testing" "    Print('In the Func2') x=func1 () y=Func2 ()Print('From func1 return is%s'%x) #from func1 return is 0Print('From func1 return is%s'%y) #from func1 return is None

Process-oriented: In the logic process defined with Def, the name of the calling function is used when stitching together

3 Why to use a function

No function is programmed just in writing logic (function), if you want to reuse your logic should not function can only be copy

#Author:zhiyu SuImport Timedeflogger (): Time_format='%y-%m-%d%x'time_current=Time.strftime (Time_format) with open ('a.txt','A +') as F:f.write ('%s End action\n'%time_current)deftest1 ():Print('Tesst1 Staring action ...') Logger ()deftest2 ():Print('test2 Staring action ...') Logger ()deftest3 ():Print('test3 Staring action ...') Logger () test1 () test2 () test3 ()

Three advantages of using functions

1. Code Reuse

2. Keep

3. Simplicity

function return value

#Author:zhiyu Sudeftest1 ():Print('In the test1')deftest2 ():Print('In the test2')    return0Print('In the test2')#Return returned value does not execute afterdeftest3 ():Print('In the test3')    return1,'Hello',['Alex','Wuqeqi'],{'name':'Alex'}x=test1 () y=test2 () z=test3 ()Print(x)#NonePrint(y)#0Print(z)#(1, ' Hello ', [' Alex ', ' Wuqeqi '],{' name ': ' Alex '})

Summarize:

return value = 0; return None

return value = 1; return object

return value >1; return tuple

Call to function

Call Method:

1.test () execution, () indicates that the call function test, () can have parameters or can not

Parameters:

1. Formal parameters and arguments

Formal parameter: Formal argument, not actual existence, is a virtual variable. Use formal parameters when defining functions and function bodies to accept arguments (the number of arguments and the type should correspond to the argument one by one) when the function is called

Arguments: Actual arguments, parameters passed to the function by the calling function, can be constants, expressions, functions, passed to the formal parameter

The difference: The formal parameter is virtual, does not occupy the memory space, the shape parametric only when is called is want $ to the memory unit, the argument is a variable occupies the memory space, the data transmits one-way, the argument passes to the parameter cannot pass the argument

2. Positional parameters and keywords (standard call: Real participation parameter one by one corresponds, keyword call: position without fixing)

3. Default parameters: Non-mandatory parameters

def Test (x,y=2):  # default parameter feature: When calling a function, the default parameter must not be forwarded to    print(x)     Print (y) Test (1,3)

4. Parameter groups

*args# List Form

*arge accepts n keyword parameter def Test (*args)    :print(args) test (1,2,3,4,5) Test (*[1,2,3,4,6])def test1 (x,*args):    Print(x)     Print (args) test1 (1,2,3,45,6)

**kwargs# convert n key parameters to a dictionary

**Kwargs to convert n keyword arguments into a dictionarydefTest2 (* *Kwargs):Print(Kwargs)Print(kwargs['name']) test2 (name='Alex', age = 8,sex='F') Test2 (**{'name':'Alex',' Age': 8})

defTest3 (name,age=18,*args,**Kwargs):Print(name)Print(age)Print(args)Print(Kwargs) Logger ('Est3')defLogger (source):Print('From %s'%source) test3 ('Alex', 151,8,hobby ='Tesla')

Note: Key parameters must be placed after the position parameter

Local variables and global variables

 def   Change_name (name):  print  ("  before change   " ,name) name  = "  alex li   " #   This function is the scope of this variable  age = PR int  ( " after changge  "  ,name) name  =  " Span style= "COLOR: #800000" >alex   " change_ Name  print  (name) 

Output

Before change alexafter changge  Alex lialex   #name改了为什么还是alex

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. You want a local variable to define a variable that can be declared by global
School ='oldboy edu.'defchange_name (name):GlobalSchool School='mage.edu'    Print('before change', Name,school) name='Alex Li'  #This function is the scope of this variableAge = 23Print('After Changge', name) name='Alex'change_name (name)Print(name)Print(school)

Note: Try not to declare the global variables in the local complex program is difficult to debug

List Dictionary Collection class data can be modified in local variables (except strings and integers)

 names = [ " alex  , "  jack  , "  rain   " ]  def   Change_name (): names[0]  = "  Golden Horn King  Span style= "COLOR: #800000" > " print  ("  inside func   " ,names) Change_name () #  inside func [' Golden Horn King ', ' Jack ', ' rain '] 
Print (names)   #[' King Horn ', ' Jack ', ' rain ']

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     nreturn calc (int (N/2) ) Calc ()output:10521

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous 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, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Function-Type 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:

(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")

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 (a,b,f):     return F (a) +f (b) Res= (Add (3,-6, ABS))print(res)

Learn Python Basics---3.1

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.