Share Python Process Control function summary

Source: Internet
Author: User
Tags set set terminates
This article shares the Python Process Control function summary

Shell script is a combination of system command, variable, process control;
Analogous to a Python program, similar to a system command that can implement many functions in the shell, Python has many modules that can implement different functions;
In terms of variables, shell scripts have system variables, common variables, special positional variables, special variable invocation methods, individual variables, and arrays, and python, like general high-level languages, has names, data types, invocation methods (operators and built-in functions);
In the process of control, the shell and a variety of high-level languages are similar, the basic Process control has a sequence, conditions, cycle three ways, mainly if,for,break,continue these ways to achieve.
The other two to deal with the basic content, in the programming thinking more profound immediately, with the process of thinking, can write a good program.

I have written a script that summarizes the Python process controls and functions, and the script reads as follows:

#!/usr/bin/env python# _*_ coding:utf-8 _*_ ################# #流程控制 ################ #print ' ' Process control is an important method of program implementation logic, Corresponds to the flowchart of the program. The general process is divided into sequence, condition, cycle three ways, sequential execution is relatively simple, with the top-down, process-oriented thinking similar, conditional judgment and circular control requires special statements and formats to achieve. Process Control statements, which are used to control the selection, circulation, and return of program processes. The main process control in Python consists of the If judgment, the for loop, the break jump, and the continue continuation statement.    "Printprint" program to control the process, it is necessary to block the program, for the code, there is a "block" and "scope" concept, most high-level programs, the program block and scope have different concepts. The program block structure is a kind of program structure, which makes the program become clear and easy to read and modify.    For example C, C + + allows programmers to follow their own habits in the non-peers, to take arbitrary alignment. A scope is a subset of programs defined by the visibility of a variable or function. If the name of a symbol is visible at the given point, the symbol is said to be within scope. For example, C, C + + uses curly braces {} to express scopes. Python uses the "indent" approach, while expressing the concept of block and scope, the same indentation within the scope of code in a program block and scope, and the same program block and scope can not be different indentation. Python uses a colon: as a block tag keyword, each colon: after the block must have the same indentation, indentation is different will be error. The high-level language allows you to define an empty scope, Python must be indented, so you can use pass to define the scope without performing any action. "print# Condition judgment print" "condition judgment, is based on the specified variable or expression results, determine the subsequent operation of the program, the most commonly used is the IF-ELSE directive, can be based on whether the condition is established to determine the subsequent procedures. If-else judgment can be executed individually or combined with multiple instructions for complex judgments. The IF statement in Python has a syntax form of 3.    #判断if格式一: If condition is true, execute a code block if expression1:block_for_true# to determine if format two: If the condition is true, then execute a block of code, if False, execute the code block under else if expression1: block_for_trueelse:block_for_false# Judge fi format three: If the condition is true, then execute a block of code;, then the condition of the elif is executed to determine if Expression1:block_for_expression1elif expression2:block_for_expression2elif expression3:block _for_expression3else:block_for_false complex Judgments, each if,elif,else block can be put into multiple statements, can also be put into judgment or circulation. Example #条件判断 if-elfi-else program: Import sysparam = Noneif len (sys.argv) > 1:param = Int (sys.argv[1]) if Param is None:pri NT "Alert" print "The Param is isn't set" Elif param < -10:print "The param is SAMLL" elif param > 10:print " The param is big "else:print" the Param is middle "#循环控制print" ' loop control because there are many regular repetitive operations in the actual program development, so some statements need to be executed repeatedly in the program. A set of repeated statements, called the loop body, can continue repeating, depending on the termination condition of the loop. The cyclic statement consists of two parts: the loop body and the cyclic termination condition. In Python, the Loop statement has both a while statement and a for statement, while the statement loops first, terminates the loop when the condition is reached, and avoids a dead loop. The For loop is preceded by a conditional judgment, which is easily avoided by the loop body after execution.  The syntax of the "printprint" while statement, when the condition is true, executes the loop body, until the expression is false, terminates execution, and the syntax is: while Expression:repeat_block ' #while循环程序示例: myList = [' 中文版 ', ' Chinese ', ' Japanese ', ' German ', ' France ']while len (myList) > 0:print "pop element out:", Mylist.pop () The For statement in print ' Python is similar to the foreach statement in C#,java, with a syntax structure of: for element in Iterable:repeat_block meaning to execute repeat_block for each element in the iterable, the current element can be accessed with the variable name element in the loop body.    The looping content can be a sequence type, a set set, or an iterator.    In developing a more complex program, the loop body of a while or for loop statement sometimes needs to end the entire loop prematurely, or start the next round before the end of the round, which requires a break or continue statement. The break statement ends the entire cycle in advance, and the continue will start the next cycle directly when the loop body is not finished. "#for循环程序示例myList = [' 中文版 ', ' Chinese ', ' Japanese ', ' German ', ' France ']for language in Mylist:print ' current El    Ement is: ", language# loop control break and Continue program example: Count=0while True: #input = Raw_input (" Enter Quit: ") input =" Quit "    # Check for valid passwd if input = = ' Quit ': Break count = count + 1 if count%3 > 0:continue Print "Please input quit!" Print "Quit loop successfully!" ################# #函数 ################ #print "from a process-oriented programming approach to functional programming, is the function in the program to play a huge role. The use of functions in programming, can write elegant program structure, modular structure, can make the program simple, improve readability and maintainability. function has three elements: function name, parameter, function body; the function can also set the return value as needed.    The key for a function definition in Python is Def, the block of the function body, or a colon: as a keyword. The return value in Python can be 0 or more, no need to display the number and type of the definition return value, just return with the return keyword, the return value is only a value, the call needs to redefine the variable to be used, the parameter of the function can be any one,Parameter name, you can define a default value for the parameter after defining the parameter name, but the parameters with default values must be followed; when calling a function, passing in the parameter values, you can pass in the parameter definition order, or you can pass in the named parameters and values in order of the parameters. "#一般函数与返回值调用示例def sum_01 (x, y): Return x+ydef total (x, Y, z): Sum_of_two = sum_01 (x, y) Sum_of_three = sum_01 (Sum_of_two, z) return su M_of_two, Sum_of_threedef main_01 (): print "Return of sum:", sum_01 (4, 6) x, y = Total (2, 6, 8) print "Return of Total: ", X,", ", ymain_01 () #带默认值的函数调用示例def sum_02 (x, y=10): Return x+ydef main_02 (): print" Return of SUM (2, 3): ", Sum_02 (2, 3) print "Return of sum ( -4)", sum_02 ( -4) main_02 () #不同方式参数赋值的函数调用示例def sum_03 (x, Y, z): return x + y + Zdef main_03 (): #下面两种调用方式, same meaning Ret1 = sum_03 (1, 2, 3) Ret2 = sum_03 (y=2, z=3, x=1) print "Return of SUM_0 3 (1, 2, 3): ", Ret1 print" Return of sum_03 (y=2, Z=3, x=1): ", ret2main_03 () Printprint" The function of the variable length parameter, is the variable number of parameters, the parameter type is indeterminate function. Variable-length parameters can provide greater flexibility for function design. Python allows the definition of two types of function variable-length parameters: Tuple tuple variable-length parameter: The number of variables that apply to unknown parameters is not fixed, but the use of these parameters in the function is not necessary to know the name of the parameter.    Expressed in the function definition with the single number *. Dictionary dict variable length parameter: The number of arguments that apply to an unknown parameter is not fixed, and you need to know the name of the parameter when the function uses parametersWord of the occasion. In the function definition, it is represented by a double model * *.  "' #使用元组tuple作为变长参数的示例def show_message (Message, *tuplename): For name in Tuplename:print message,", ", Namedef Main_tuple (): Show_message ("Good morring", "Jack", "Evans", "Rose Hasa", 893, "Zion") main_tuple () #使用字典dict作为变长参数的示例de F Check_book (**dictparam): If Dictparam.has_key (' Price '): "Price = int" (dictparam[' Price ")) If price > 100:print "*******i want buy this book!*******" print "The book information is as follow:" for key in D Ictparam.keys (): Print Key, ":", Dictparam[key] print "" Def main_dict (): Check_book (author = ' James ',  title = ' Economics Introduction ') check_book (author = ' Linda ', title = ' Deepin in python ', Date = ' 2015-5-1 ', Price = 302) Check_book (Date = ' 2002-3-19 ', Title = ' Cooking book ', Price =) Check_book (author = ' Jinker Landy ', tit Le = ' How to keep healthy ') check_book (Category = ' Finance ', Name = ' Enterprise Audit ', Price = $) main_dict () print PriThe NT ' anonymous function Anonymous function is a class of functions or subroutines that do not need to define a function name, and is typically used where the value has a function reference in the code. Because only one reference is required, there is no need to declare it. In Python, you use the lambda syntax to define an anonymous function, just an expression, without declaring it. In addition to the absence of a parameter name, the definition of an anonymous function is the same as a generic function. The anonymous function defines the following format: Lambda [arg1, arg2, ..., ArgN]: Expressionprint (lambda x, y:x-y) (3, 4) "#匿名函数示例如下import Datetimedef Namefu     NC (a): Return "I ' m named function with param%s"% a def call_func (func, param): Print datetime.datetime.now () Print func (param) print "" Def Main_lambda (): Call_func (namefunc, ' Hello ') call_func (Lambda x:x*2, 9) call _func (Lambda Y:y*y,-4) Main_lambda ()

The

Execution results are as follows:

# python func.py Process Control is an important method of program implementation logic, which corresponds to the flowchart of the program. The general process is divided into sequence, condition, cycle three ways, sequential execution is relatively simple, with the top-down, process-oriented thinking similar, conditional judgment and circular control requires special statements and formats to achieve. Process Control statements, which are used to control the selection, circulation, and return of program processes. The main process control in Python consists of the If judgment, the for loop, the break jump, and the continue continuation statement.    Program to control the process, it is necessary to block the program, for the code, there is the concept of "block" and "scope", most of the high-level programs, the program block and scope have different concepts. The program block structure is a kind of program structure, which makes the program become clear and easy to read and modify.    For example C, C + + allows programmers to follow their own habits in the non-peers, to take arbitrary alignment. A scope is a subset of programs defined by the visibility of a variable or function. If the name of a symbol is visible at the given point, the symbol is said to be within scope. For example, C, C + + uses curly braces {} to express scopes. Python uses the "indent" approach, while expressing the concept of block and scope, the same indentation within the scope of code in a program block and scope, and the same program block and scope can not be different indentation. Python uses a colon: as a block tag keyword, each colon: after the block must have the same indentation, indentation is different will be error. The high-level language allows you to define an empty scope, Python must be indented, so you can use pass to define the scope without performing any action. Conditional judgment, according to the result of the specified variable or expression, determines the subsequent operation of the program, the most commonly used is the IF-ELSE directive, can be based on whether the condition is established to determine the subsequent procedures. If-else judgment can be executed individually or combined with multiple instructions for complex judgments. The IF statement in Python has a syntax form of 3.    #判断if格式一: If condition is true, execute a code block if expression1:block_for_true# to determine if format two: If the condition is true, then execute a block of code, if False, execute the code block under else if expression1: block_for_trueelse:block_for_false# Judge fi format three: If the condition is true, then execute a block of code, if False, then perform the elif condition to determine if expression1:block_for_ Expression1elif Expression2:block_for_expression2elif Expression3:    Block_for_expression3else:block_for_false complex Judgments, each if,elif,else block can be put into multiple statements, can also be put into judgment or loop. Alertthe param is not set loop control because there are many regular repetitive operations in the actual program development, so some statements need to be executed repeatedly in the program. A set of repeated statements, called the loop body, can continue repeating, depending on the termination condition of the loop. The cyclic statement consists of two parts: the loop body and the cyclic termination condition. In Python, the Loop statement has both a while statement and a for statement, while the statement loops first, terminates the loop when the condition is reached, and avoids a dead loop. The For loop is preceded by a conditional judgment, which is easily avoided by the loop body after execution. While the syntax of the statement, the condition is true, the execution of the loop body, until the expression is false, terminate execution, syntax is: while Expression:repeat_blockpop element out:francepop element Out:ge The For statement in Rmanpop element out:japanesepop element out:chinesepop element Out:englishpython is similar to the foreach statement in C#,java, The syntax structure is: for element in Iterable:repeat_block meaning to execute repeat_block for each element in the iterable, the current element can be accessed with the variable name element in the loop body.    The looping content can be a sequence type, a set set, or an iterator.    In developing a more complex program, the loop body of a while or for loop statement sometimes needs to end the entire loop prematurely, or start the next round before the end of the round, which requires a break or continue statement. The break statement ends the entire cycle in advance, and the continue will start the next cycle directly when the loop body is not finished. Current element is:englishcurrent element is:chinesecurrent element is:japanesecurrent element is:germancurrent El Ement Is:francequit Loop successfully! from a process-oriented programming approach to functional programming, is the functionPlay a huge role in the program. The use of functions in programming, can write elegant program structure, modular structure, can make the program simple, improve readability and maintainability. function has three elements: function name, parameter, function body; the function can also set the return value as needed.    The key for a function definition in Python is Def, the block of the function body, or a colon: as a keyword. The return value in Python can be 0 or more, no need to display the number and type of the definition return value, just return with the return keyword, the return value is only a value, the call needs to redefine the variable to use, the function can be any argument, you can define the parameter name, you can also define the parameter name, Define a default value for the parameter, but the parameter with the default value must be in the back; when calling a function, passing in a parameter value, you can pass in the value of the parameter definition only, or you can pass in the named parameter and value without order; Return of Sum:10return of Total:8, 16return O F Sum (2, 3): 5return of sum ( -4) 6return of sum_03 (1, 2, 3): 6return of Sum_03 (y=2, Z=3, x=1): 6 The function of variable-length parameter, which is a function of the changeable parameter number and indefinite parameter type 。 Variable-length parameters can provide greater flexibility for function design. Python allows the definition of two types of function variable-length parameters: Tuple tuple variable-length parameter: The number of variables that apply to unknown parameters is not fixed, but the use of these parameters in the function is not necessary to know the name of the parameter.    Expressed in the function definition with the single number *. Dictionary dict variable length parameter: The number of unknown parameters is not fixed, and when the function uses parameters need to know the name of the parameter. In the function definition, it is represented by a double model * *. Good morring, Jackgood morring, Evansgood morring, Rose hasagood morring, 893Good morring, zionthe book Informat Ion is as Follow:Title:Economics introductionauthor:james*******i want buy this book!*******the book information ar E as Follow:date:2015-5-1price:302title:deepin in pythonauthor:lindathe Book information is as follow:date:2002-3-19price:20title:cooking bookthe book information is as Follow:title  : How to keep Healthyauthor:jinker landy*******i want buy the Book!*******the book information is as Follow:category : financeprice:105name:enterprise Audit anonymous function Anonymous function is a class of functions or subroutines that do not need to define a function name, and is typically used where the value has a function reference in the code. Because only one reference is required, there is no need to declare it. In Python, you use the lambda syntax to define an anonymous function, just an expression, without declaring it. In addition to the absence of a parameter name, the definition of an anonymous function is the same as a generic function. The anonymous function defines the following format: Lambda [arg1, arg2, ..., ArgN]: Expressionprint (lambda x, y:x-y) (3, 4) 2017-03-09 20:20:31.264415 I ' m named function with param hello2017-03-09 20:20:31.264533182017-03-09 20:20:31.26455516

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.