Summary of python process control functions

Source: Internet
Author: User
Tags define function
This article describes the summary of python process control functions. This article shares the summary of python process control functions.

Shell scripts are composed of system commands, variables, and process control;
Similar to python programs, python has many modules that can implement different functions, similar to system commands that can implement many functions in shell;
In terms of variables, shell scripts have System variables, including common variables, special location variables, special variable calling methods, single variables, and arrays. python is the same as general high-level languages, variables include names, data types, and calling methods (operators and built-in functions );
In terms of process control, shell is similar to various advanced languages. The basic process control includes three methods: order, condition, and loop, which are mainly if, for, break, continue.
In addition, the two processes the basic content, in terms of programming ideas should be more profound and immediate, with the program thinking, can write a good program.

I wrote a script to summarize python process control and functions. the script content is as follows:

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ ################## process control ################ # print ''' process control, it is an important method for program implementation logic, and corresponds to the program flowchart. The general process can be divided into three methods: order, condition, and loop. the sequential execution is relatively simple. the process-oriented approach is similar to the process-oriented approach, conditional judgment and loop control require special statements and formats. Process control statements are used to control the selection, loop, and return of program processes. The main process control in python includes statements such as if judgment, for loop, break jump out, and continue. '''Printprinting''' to control the process, the program must be segmented. for the code, there is a concept of "program block" and "scope". In most advanced programs, block and scope have different concepts. The block structure is a program structure that makes the program clear and easy to read and modify. For example, C and C ++ allow programmers to use arbitrary alignment between different rows according to their habits. Scope is a subset of programs defined according to the visibility of variables or functions. If the name of a symbol is visible at a given point, the symbol is within the scope. For example, C and C ++ use braces {} to express the scope. In python, the "indent" method is used to express the concept of program blocks and scopes at the same time. the code within the same indentation range is in a program block and scope, the same block and scope cannot have different indentation. In python, Colon: is used as the program block to mark keywords. Each colon: The program block must have the same indentation. if the indentation is different, an error is returned. The advanced language allows defining an empty scope. python must have indentation. Therefore, you can use pass to define the scope without executing any action. '''Print # print ''' is used to determine the program to run in the future based on the results of the specified variable or expression. The most commonly used is the if-else command, you can determine the subsequent procedures based on the conditions. If-else judgment can be executed in a single way, or multiple commands can be combined for complex judgment. The if statement in python has the syntax format of 3. # Determine if Format 1: if condition is true, execute a code block if expression1: block_for_True # determine if Format 2: if condition is true, execute a code block. if the condition is false, run the code block in else if expression1: block_for_Trueelse: block_for_False # determine the fi format. 3. if the if condition is true, run the code block. if the condition is false, if expression1: when expression2: block_for_expression2elif expression3: block_for_expression3else: block_for_False, multiple statements can be placed in each if, elif, or else block, it can also be placed in a judgment or loop. ''' # if-elfi-else program example: import sy Sparam = Noneif len (sys. argv)> 1: param = int (sys. argv [1]) if param is None: print "Alert" print "The param is not set" elif param <-10: print "The param is samll" elif param> 10: print "The param is big" else: print "The param is middle" # loop control print '', because in actual program development, there are many regular repeated operations, so some statements need to be repeated in the program. A group of statements that are repeatedly executed is called the loop body. whether the statement can be repeated or not depends on the termination condition of the loop. A loop statement consists of a loop body and a loop termination condition. In python, there are two types of loop statements: the while statement and the for statement. The while statement first loops and terminates the loop when the condition is reached. to avoid endless loops. The for loop first has a conditional judgment, followed by the execution of the loop body, it is easy to avoid endless loops. '''Printprint ''' the syntax of the while Statement. if the judgment condition is true, the loop body is executed until the expression is false and the execution is terminated. The syntax is: while expression: repeat_block ''' # Example of a while loop program: myList = ['English ', 'China', 'shanghaiese', 'German', 'France '] while len (myList)> 0: print "pop element out:", myList. the for statement in pop () print ''' python is similar to the foreach statement in C # and java. the syntax structure is: for element in iterable: repeat_block indicates executing repeat_block for each element in iterable. in the loop body, you can use the variable name element to access the current element. The cyclic content can be a sequence type, set, or iterator. When developing complex programs, the loop body of the while or for loop statements sometimes needs to end the entire loop in advance or start the next loop before the current round ends, this requires the break or continue statement. The break statement ends the entire loop ahead of schedule. the continue starts the next loop directly when the current loop body does not end. ''' # For loop program example myList = ['English ', 'China', 'shanghaiese', 'German', 'France '] for language in myList: print "Current element is:", language # Example of loop control break and continue Program: count = 0 while 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! "################# Functions ################## print'' 'process-oriented programming methods, function programming plays a huge role in the program. In programming, functions can be used to write elegant program structures and modular structures. This simplifies the program and improves readability and maintainability. A function has three elements: function name, parameter, and function body. you can set the return value as needed. In python, the key word defined by a function is def. the Function Block uses the colon (:) as the key word. In python, the return values can be 0 or more. you do not need to display the number and type of the defined return values. you only need to use the return keyword to return the values. you need to redefine the variables before using the return values; function parameters can be any one. you can only define the parameter name, or you can define the default value for the parameter after defining the parameter name, but the parameters with the default value must be followed; when calling a function and passing in parameter values, you can pass in only the values in the parameter definition order, or pass in the named parameters and values without the order; ''' # example of calling general functions and return values 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 sum_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 () # function call example def sum_02 (x, y = 10) with default values ): 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 () # function call example def sum_03 (x, y, z): return x + y + zdef main_03 () with different parameter assignment methods (): # The following two call methods have the same meaning: ret1 = sum_03 (1, 2, 3) ret2 = sum_03 (y = 2, z = 3, x = 1) print "return of sum_03 (1, 2, 3):", ret1 print "return of sum_0 3 (y = 2, z = 3, x = 1): ", ret2main_03 () printprint ''' function for variable-length parameters. it is a function with variable numbers and variable parameter types. Variable-length parameters can provide more flexibility for function design. In python, two types of function variable length parameters can be defined: tuple variable length parameter, which is applicable to scenarios where the number of unknown parameters is not fixed, but the parameter names are not required to be used in functions. The asterisk (*) is used in the function definition. Dictionary dict variable length parameter: this parameter is applicable to scenarios where the number of unknown parameters is not fixed and the parameter name needs to be known when the function uses parameters. In the function definition, double Model ** is used. ''' # Example of using tuple as the variable length parameter 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 () # example of using the dictionary dict as the variable length parameter def 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 are as follow: "for key in dictParam. keys (): print key, ":", dictParam [key] print "def main_dict (): check_book (author = 'James ', Title = 'economist Introduction ') check_book (author = 'Linda ', Title = 'deepin Python', Date = '2017-5-1', Price = 2015) check_book (Date = '2017-3-19 ', title = 'cooking book', Price = 20) check_book (author = 'jinker landy ', Title = 'How to keep healthy ') check_book (Category = 'finance', Name = 'Enterprise Audit ', Price = 105) main_dict () printprint ''' the Anonymous Function is a type of Function or subroutine that does not need to define the Function name. it is generally used when values are referenced by the callback Function in the code. Because it only needs to be referenced once, it does not need to be declared. In python, the lambda syntax is used to define anonymous functions. only expressions are required, and no declaration is required. Except for the parameter name, the anonymous function definition is the same as the general function definition. The definition format of an anonymous function is as follows: lambda [arg1, arg2 ,..., argN]: expressionprint (lambda x, y: x-y) (3, 4) ''' # Example of an anonymous function: import datetimedef nameFunc (): 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 result is as follows:

# Python func. py process control is an important method for program implementation logic, which corresponds to the program flowchart. The general process can be divided into three methods: order, condition, and loop. the sequential execution is relatively simple. the process-oriented approach is similar to the process-oriented approach, conditional judgment and loop control require special statements and formats. Process control statements are used to control the selection, loop, and return of program processes. The main process control in python includes statements such as if judgment, for loop, break jump out, and continue. To control the process, the program must be segmented. for the code, there is a concept of "program block" and "scope". In most advanced programs, block and scope have different concepts. The block structure is a program structure that makes the program clear and easy to read and modify. For example, C and C ++ allow programmers to use arbitrary alignment between different rows according to their habits. Scope is a subset of programs defined according to the visibility of variables or functions. If the name of a symbol is visible at a given point, the symbol is within the scope. For example, C and C ++ use braces {} to express the scope. In python, the "indent" method is used to express the concept of program blocks and scopes at the same time. the code within the same indentation range is in a program block and scope, the same block and scope cannot have different indentation. In python, Colon: is used as the program block to mark keywords. Each colon: The program block must have the same indentation. if the indentation is different, an error is returned. The advanced language allows defining an empty scope. python must have indentation. Therefore, you can use pass to define the scope without executing any action. Conditional judgment is based on the results of the specified variable or expression to determine the program to run in the future. The most common is the if-else command, which can determine the subsequent program based on the condition. If-else judgment can be executed in a single way, or multiple commands can be combined for complex judgment. The if statement in python has the syntax format of 3. # Determine if Format 1: if condition is true, execute a code block if expression1: block_for_True # determine if Format 2: if condition is true, execute a code block. if the condition is false, run the code block in else if expression1: block_for_Trueelse: block_for_False # determine the fi format. 3. if the if condition is true, run the code block. if the condition is false, if expression1: when expression2: block_for_expression2elif expression3: block_for_expression3else: block_for_False, multiple statements can be placed in each if, elif, or else block, it can also be placed in a judgment or loop. alertThe param is not set because In program development, there are many regular repeated operations, so some statements need to be repeated in the program. A group of statements that are repeatedly executed is called the loop body. whether the statement can be repeated or not depends on the termination condition of the loop. A loop statement consists of a loop body and a loop termination condition. In python, there are two types of loop statements: the while statement and the for statement. The while statement first loops and terminates the loop when the condition is reached. to avoid endless loops. The for loop first has a conditional judgment, followed by the execution of the loop body, it is easy to avoid endless loops. When the while statement syntax determines that the condition is true, the loop body is executed until the expression is false and the execution is terminated. The syntax is: while expression: repeat_blockpop element out: Francepop element out: Germanpop element out: in Japanesepop element out: Chinesepop element out: for statements in Englishpython are similar to those in C # and foreach statements in java. the syntax structure is: for element in iterable: repeat_block indicates executing repeat_block for each element in iterable. in the loop body, you can use the variable name element to access the current element. The cyclic content can be a sequence type, set, or iterator. When developing complex programs, the loop body of the while or for loop statements sometimes needs to end the entire loop in advance or start the next loop before the current round ends, this requires the break or continue statement. The break statement ends the entire loop ahead of schedule. the continue starts the next loop directly when the current loop body does not end. Current element is: EnglishCurrent element is: ChineseCurrent element is: JapaneseCurrent element is: GermanCurrent element is: FranceQuit loop successfully! From process-oriented programming methods to functional programming, functions play a huge role in the program. In programming, functions can be used to write elegant program structures and modular structures. This simplifies the program and improves readability and maintainability. A function has three elements: function name, parameter, and function body. you can set the return value as needed. In python, the key word defined by a function is def. the Function Block uses the colon (:) as the key word. In python, the return values can be 0 or more. you do not need to display the number and type of the defined return values. you only need to use the return keyword to return the values. you need to redefine the variables before using the return values; function parameters can be any one. you can only define the parameter name, or you can define the default value for the parameter after defining the parameter name, but the parameters with the default value must be followed; when calling a function and passing in a parameter value, you can pass in only the value in the parameter definition order, or pass in the name parameter and value without the order; return of sum: 10 return of total: 8, 16 return of sum (2, 3): 5 return of sum (-4) 6 return of sum_03 (1, 2, 3): 6 return of sum_03 (y = 2, z = 3, x = 1): 6. a variable-length function is a function with variable numbers and variable parameter types. Variable-length parameters can provide more flexibility for function design. In python, two types of function variable length parameters can be defined: tuple variable length parameter, which is applicable to scenarios where the number of unknown parameters is not fixed, but the parameter names are not required to be used in functions. The asterisk (*) is used in the function definition. Dictionary dict variable length parameter: this parameter is applicable to scenarios where the number of unknown parameters is not fixed and the parameter name needs to be known when the function uses parameters. In the function definition, double Model ** is used. Good Morring, JackGood Morring, EvansGood Morring, Rose HasaGood Morring, 893 Good Morring, ZionThe book information are as follow: Title: Economics Introductionauthor: james ******* I want buy this book! * ***** The book information are as follow: Date: 2015-5-1Price: 302 Title: Deepin in pythonauthor: LindaThe book information are as follow: Date: 2002-3-19Price: 20 Title: cooking bookThe book information are as follow: Title: How to keep healthyauthor: Jinker Landy ******* I want buy this book! * ***** The book information are as follow: Category: FinancePrice: 105 Name: Enterprise Audit Anonymous Function is a class of functions or subprograms that do not need to define Function names, it is generally used when values are referenced by the callback function in the code. Because it only needs to be referenced once, it does not need to be declared. In python, the lambda syntax is used to define anonymous functions. only expressions are required, and no declaration is required. Except for the parameter name, the anonymous function definition is the same as the general function definition. The definition format of an anonymous function is as follows: lambda [arg1, arg2 ,..., argN]: expressionprint (lambda x, y: x-y) (3, 4) 20:20:31. 264415 I'm named function with param hello2017-03-09 20:20:31. 264533182017-03-09 20:20:31. 26455516

The above is a summary of the python process control function. For more information, see other related articles in the first PHP community!

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.