AUTOMATE THE BORING STUFF WITH PYTHON study notes - Chapter 3: FUNCTIONS

Function (function) is a subroutine program, similar to a black box. The function code is a function of complete tissue together for the purpose of reuse.
Use functions can also be easy to debug errors.

DEF statement with parameters

def function_name(parameters):
	code block

Function parameters are called definition parameter (parameters), the parameters passed when calling a function called arguments (arguments)
to pass arguments are of By Value.

RETURN statement and return value

return value | expression

The following functions can be defined according to the conditions return different data types, although the syntax right, but not recommended:

>>> def getAnswer(answerNumber):
...     if answerNumber == 1:
...             return 'It is certain'
...     elif answerNumber == 2:
...             return 2

Null

The Python null value Nonerepresents, similar to other languages Nullor Nil.
Null indicates that no assignment, the lack of value.
Function returns no value, such as print () return value None, in fact, added Python statement return None of these functions, in addition, return statements without parameters is equivalent to return None.

KEYWORD parameters and the PRINT () function

Function parameters are usually transmitted by location, but can be specified keyword parameters, for example:
function_name(keyword=argument, keyword=argument...)
keyword parameter is typically a function for optional parameters.

Look at the definition print function:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The following is an example:

>>> print('cats', 'dogs', 'mice')
cats dogs mice
>>> print('cats', 'dogs', 'mice', end='!\n')
cats dogs mice!
# 默认的print类似于echo,下面这句类似echo -n
>>> print('Hello', end='')
>>> print('cats', 'dogs', 'mice', sep = '|')
cats|dogs|mice

Call Stack

Similar to the function call stack, LIFO.

Local and global scope

Local variables inside a function called variable, the effective range of the local (internal function); variables outside the function called global variables, the effective range is global (whole program).
After the scope of the variable becomes invalid (believed to be destroyed, the end of the life cycle).

Some guidelines:

  • Global scope of the code can not access the local variables
  • Local scope code access global variables, local variables itself, but can not access local variables other functions
  • Effective range of different variables can be the same name, but should be avoided

GLOBAL statement

If the function, the variable is not assigned nor used directly passed through parameters, then the variable is a global variable.
If you want to modify global variables in the function, you must use the global statement, for example:

def spam():
	global eggs
    eggs = 'spam'

Exception Handling

Herein refers to an abnormal exception, it can be try...excepttreated. E.g:

try:
	code block for operation
except EXCEPTION:
	code block for handle exception

Applet: ZIGZAG

Code zigzag.pyas follows:

import time, sys
indent = 0 # How many spaces to indent.
indentIncreasing = True # Whether the indentation is increasing or not.

try:
    while True: # The main program loop.
        print(' ' * indent, end='')
        print('********')
        time.sleep(0.1) # Pause for 1/10 of a second.

        if indentIncreasing:
            # Increase the number of spaces:
            indent = indent + 1
            if indent == 20:
                # Change direction:
                indentIncreasing = False
        else:
            # Decrease the number of spaces:
            indent = indent - 1
            if indent == 0:
                # Change direction:
                indentIncreasing = True
except KeyboardInterrupt:
    sys.exit()

The only explanation is KeyboardInterruptabnormal indicates key Ctrl+C.

word

meandering - winding, circuitous
upshot - the final results, the outcome

Published 370 original articles · won praise 43 · views 550 000 +

Guess you like

Origin blog.csdn.net/stevensxiao/article/details/104089485