Process Control
In addition to the while statement described earlier, Python has more process control tools.
If statement
>>> x = Int (raw_input ("Please enter a integer:")) Please enter an integer:42>>> if x < 0: ... x = 0 ... print ' negative changed to zero ' ... elif x = = 0: ... print ' zero ' ... elif x = = 1: ... else: '. print ' More ' ... More
There may be 0 to more elif sections, and else is optional. The keyword ' elif ' is an abbreviation for ' else if ', which avoids too deep indentation. The If ... elif. Elif sequence is used to replace a switch or case statement in another language. There is no case language in Python and you can consider replacing it with a dictionary or elif statement.
For statement
The Python for statement loops through the children in the sequence (list or string, etc.) and iterates in the order in which they are in the sequence.
>>> # Measure Some strings: ... words = [' cat ', ' window ', ' Defenestrate ']>>> for w in words: .... print W, Len (w) ... cat 3window 6defenestrate 12
Modifying the iteration sequence during an iteration is unsafe and may cause some elements to repeat two times, and it is recommended that you first copy:
>>> for W in words[:]: # Loop over a slice copy of the entire list .... If Len (w) > 6: ... words.in SERT (0, W) ...>>> words[' defenestrate ', ' Cat ', ' window ', ' defenestrate ']
Range () function
Built-in function range () generates a series of linear values:
>>> Range (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Range (10) generates a linked list with 10 values, but does not contain the rightmost value. By default, starting with 0, you can also let range start with another value, or specify a different increment value (even a negative number, sometimes called a "step"):
>>> Range (5, 7, 8, 9]>>> range (0, 6, 3) [0, 3, 6, 9]>>> range (-10,-100,-30) [-10, 4 0, -70]>>> Range (-10,-100, 30) []
If you need an index and a value for the iteration, use range () and Len () together:
>>> a = [' Mary ', ' had ', ' a ', ' little ', ' lamb ']>>> for I in range (Len (a)): ... print i, a[i] ... 0 Mary1 had2 A3 little4 Lamb
However, it is more convenient to use enumerate (), see the following introduction.
Break and continue statements and ELSE clauses in loops
The
Break statement is similar to C, and is used to terminate the current for or while loop. The
Loop may have an ELSE clause, which executes when the loop iterates through the entire list (for), or when the condition is false (for the while), but does not execute when the loop is break. This is similar to the try...else rather than the if...else. See the procedure for finding primes:
>>> for n in range (2, 10):... for x In range (2, n): if n % x == 0:... print n, ' equals ', x, ' * ', n/x... break... else:... # loop fell through without finding a factor... print n, ' Is a prime number ' ... 2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49&nBsp;equals 3 * 3
The continue statement also comes from C, which means exiting the secondary loop and continuing with the next iteration. You can usually use If...else instead, see Find an even-numbered instance:
>>> for Num in range (2): ... if num% 2 = = 0: ... print "Found an even number", num ... Continue. Print "Found a number", numfound an even number 2Found a number 3Found an even number 4Found a number 5Fou nd an even number 6Found a number 7Found an even number 8Found a number 9
Pass
The pass statement does nothing. It is syntactically necessary, but practically nothing is done on the occasion, also often the term is later reserved later extended. For example:
>>> while True: ... pass # busy-wait for keyboard interrupt (CTRL + C) ...>>> class Myemptyclass: ... Pass...>>> def initlog (*args): ... pass # Remember to implement this!...
Defining functions
The function of the Fibonacci sequence:
>>> def fib (n): # write Fibonacci series up to n... "" " Print a fibonacci series up to n. "" " ... a, b = 0, 1... while a < n:... print a,... a, b = b, a+b...>>> # now call &NBSP;THE&NBSP;FUNCTION&NBSP;WE&NBSP;JUST&NBSP;DEFINED:...&NBSP;FIB (0 1 1 2 3 5) 8 13 21 34 55 89 144 233 377 610 987 1597
The keyword def introduces a function definition followed by a functional name and formal parameters contained in parentheses. The function body statement starts at the next line and must be indented.
The first line of the function body can be an optional string literal, which is the document string. Some tools automatically generate documents via Docstrings, or allow users to interactively browse through code, and it's a good practice to add a document string.
A symbol table is used to store local variables when the function executes. To be exact, the variable assignments for all functions are stored in the local symbol table. The order of the variables to be found, first local, then step up, then to the global variable, the last built-in name. Global variables can be consumed locally, but cannot be directly assigned (unless declared with global), although they can be referenced, because Python will redefine a local variable at local assignment.
The actual parameters of the function introduce a local symbol table when called, that is, a value call (the value is always an object reference, not the value of the object).
The function definition introduces a function name within the current symbol table. The value of the function name is the type of the user-defined function, which can be assigned to other variables as function aliases.
>>> fib<function fib at 10042ed0>>>> f = fib>>> F (100) 0 1 1 2 3 5 8 13 21 34 55 89
A function that does not have a return statement also returns none. The interpreter typically does not display none unless printed with print.
>>> fib<function fib at 10042ed0>>>> f = fib>>> F (100) 0 1 1 2 3 5 8 13 21 34 55 89
Returning from the function
>>>&NBSP;DEF&NBSP;FIB2 (n): # return fibonacci series up to n ... "" "Return a list containing the fibonacci series up to n. "" " ... result = []... a, b = 0 , 1... while a < n:... result.append (a) # see below... a, b = b, a+b... return RESULT...>>>&NBSP;F100&NBSP;=&NBSP;FIB2 ( # call it>>>) f100 # write the result[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
The return statement returns a value from the function, and return without an expression returns none. None will be returned when the process is finished.
Statement Result.append (b) is called a method that calls a list. A method is a function that belongs to an object, such as Obj.methodename,obj is an object (possibly an expression), and MethodName is the method name of the object. Different types have different methods. Different types may have methods with the same name. Append () attaches an element to the tail of the linked list, equivalent to result = result + [b], but is more efficient.
Deep python function definition
Python's function parameters are available in three ways.
Default parameters
The most common way is to specify a default value for the parameter, which can be passed less when called:
DEF&NBSP;ASK_OK (prompt, retries=4, complaint= ' yes or no, please! '): while true: ok = raw_input (Prompt) if ok in (' y ', ' ye ', ' yes '): return True if ok in (' n ', ' no ', ' nop ', ' nope '): return False retries = retries - 1 if retries < 0: raise ioerror (' Refusenik user ') print complaint
Call Mode:
Only required parameters are given: ASK_OK (' Do you really want to quit? ')
An optional parameter is given: Ask_ok (' OK to overwrite the file? ', 2)
Give all the parameters: Ask_ok (' OK to overwrite the file? ', 2, ' Come on, only yes or no! ')
The IN keyword measures whether the sequence contains the specified value.
The default value is passed in when the function is defined, as follows:
i = 5def f (arg=i): Print Argi = 6f ()
The example above shows 5.
Note: The default value is assigned only once. The result is different when the default value is a Mutable object (such as a list, dictionary, or an instance of most classes). Instance:
Def f (A, l=[]):
L.append (a)
Return L
Print f (1)
Print F (2)
Print F (3)
Execution Result:
[1]
[1, 2]
[1, 2, 3]
Evasion mode:
Def f (A, L=none):
If L is None:
L = []
L.append (a)
Return L
Keyword parameters
The form of the keyword parameter: keyword = value.
def parrot (Voltage, state= ' a stiff ', action= ' voom ', type= ' Norwegian Blue '):
Print "--this parrot wouldn ' t", action,
Print "If you put", voltage, "volts through it."
Print "--lovely plumage, the", type
Print "--It ' s", State, "!"
Valid invocation:
Parrot ($) # 1 positional argument
Parrot (voltage=1000) # 1 keyword argument
Parrot (voltage=1000000, action= ' Vooooom ') # 2 keyword arguments
Parrot (action= ' vooooom ', voltage=1000000) # 2 keyword arguments
Parrot (' A million ', ' bereft of life ', ' Jump ') # 3 positional arguments
Parrot (' A Thousand ', state= ' pushing up the Daisies ') # 1 positional, 1 keyword
Invalid call
Parrot () # No required parameters
Parrot (voltage=5.0, ' dead ') # key parameter followed by non-keyword parameter
Parrot (voltage=220) # Repeat specified value for same parameter
Parrot (actor= ' John Cleese ') # incorrect keyword parameter name
Keyword parameter after the position parameter, the order of multiple keyword parameters is independent, one parameter can only specify one time value, error instance:
>>> def function (a):
... pass
...
>>> function (0, a=0)
Traceback (most recent):
File "<stdin>", line 1, in?
Typeerror:function () got multiple values for keyword argument ' a '
The last one if there are two asterisks (such as name) to receive a dictionary, the stored form parameter has no parameter name and value defined. A similar single asterisk such as *name indicates that a tuple is accepted.
def cheeseshop (Kind, *arguments, **keywords):
Print "--do you had any", kind, "?"
Print "--I ' m Sorry, we ' re all out of", kind
For ARG in arguments:
Print arg
Print "-" * 40
Keys = sorted (Keywords.keys ())
For KW in keys:
Print kw, ":", keywords[kw]
Call
Cheeseshop ("Limburger", "It ' s very runny, sir.",
"It ' s really very, very runny, sir.",
Shopkeeper= ' Michael Palin ',
client= "John Cleese",
Sketch= "Cheese Shop Sketch")
Perform:
-Does any Limburger?
--I ' m Sorry, we ' re all out of Limburger
It ' s very runny, sir.
It ' s really very, very runny, sir.
----------------------------------------
Client:john Cleese
Shopkeeper:michael Palin
Sketch:cheese Shop Sketch
Note that the order of the parameters is random and can be sorted using sort.
Any parameter list
def write_multiple_items (file, separator, *args):
File.write (Separator.join (args))
Parameter list unpacking
Splits a list or tuple into multiple, parallel arguments.
>>> Range (3, 6) # Normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> Range (*args) # arguments unpacked from a list
[3, 4, 5]
The same dictionary can be unpacked with two asterisks:
>>> def parrot (voltage, state= ' a stiff ', action= ' Voom '):
... print "--this parrot wouldn ' t", action,
... print "If you put", voltage, "volts through it.",
... print "E ' s", State, "!"
...
>>> d = {"Voltage": "Four Million", "state": "Bleedin ' demised", "Action": "Voom"}
>>> Parrot (**d)
--This parrot wouldn ' t voom if you put a four million volts through it. E ' s bleedin ' demised!
Lambda expression
The Lambda keyword creates a short, anonymous function that has only one row and can be used when it is created. such as summation: Lambda A, b:a+b. It is generally not recommended to use:
>>> def make_incrementor (n):
... return lambda x:x + N
...
>>> f = make_incrementor (42)
>>> F (0)
42
>>> F (1)
43
In addition to returning an expression, lambda can also be used as a function parameter.
>>> pairs = [(1, ' One '), (2, ' One '), (3, ' three '), (4, ' four ')]
>>> Pairs.sort (Key=lambda pair:pair[1])
>>> pairs
[(4, ' Four '), (1, ' One '), (3, ' three '), (2, ' both ')] (1)
43
Document string
The contents and format of the document string are suggested below.
The purpose of the first brief introduction of the object. You cannot describe information that can be found elsewhere, such as object names and types, and capitalize the first letter.
If the document string has more than one line, the second behaves as a blank line to separate the overview and other descriptions. Describes calling conventions, boundary effects, and so on.
The Python interpreter does not remove indents from the multiline document string and is handled with a tool. The Convention is as follows: The first non-empty line after the first line determines the indentation of the entire document. Instance:
>>> def my_function ():
... "" does nothing, but document it.
...
... No, really, it doesn ' t do anything.
... """
... pass
...
>>> Print my_function.__doc__
Do nothing, but document it.
No, really, it doesn ' t do anything.
Coding style
Recommended adherence to PEP8, high readability, some key points are as follows:
Use 4 spaces to indent rather than tab.
No more than 79 characters per line.
Use empty lines to separate functions and classes, and large blocks of code in functions.
If possible, the comment takes up one line
Working with document Strings
The operator has a space before and after the comma, but there are no spaces on either side of the parentheses. such as: a = f (1, 2) + g (3, 4).
Uniform functions and class naming. The class name is a camel with an initial capitalization, such as CamelCase. Function and method names are made up of lowercase and underscores: lower_case_with_underscores. Use self in a class.
Don't use fancy coding for internationalization.
Introduction to Automated testingPyautoguiResources
Author Blog: http://my.oschina.net/u/1433482
-
contact Xu Rongzhong python development Automation test group 113938272 Weibo Http://weibo.com/cizhenshi.
Python 2.7 Official English tutorial: https://docs.python.org/2/tutorial/
Python 2.7 Chinese tutorials and automated Testing introduction (2)