Python basis of recursion, variable scope and exceptions

Recursion

  • Conditions must be recursive boundary conditions, stop recursion
  • To Fibonacci number, for example, is 0 or 1 exit
def fib(n):
    if n == 0 or n == 1:
        return n
    else:
        return fib(n - 1) + fib(n - 2)
def hanoi(a,b,c,n):
    if n == 1:
        print(a,'->',c)
    else:
        hanoi(a,c,b,n-1)#借由c先移动到b上
        print(a,'->',c)
        hanoi(b,a,c,n-1)#出口是n=1时
def foo(num,base):
    if num >= base:
      foo(num // base, base)
    print(num % base, end = ' ')
foo(126,2)
1 1 1 1 1 1 0

Variable Scope

Global Variables
  • The body portion of the program code is a global variable
  • Global and local variables with the same name, follow the principle of the inner shielding layer
  • Modify its value to a global variable is not in the function
a = 3
def f():
    a = 5
    print(a ** 2)
25
  • The global statement stressed that global variables
def f(x):
    global a
    print(a)
    a = 5
    print(a + x)
a = 3
f(8)
print(a)
3
13
5
Local variables
  • Variables are local variables in the function

abnormal

  • BaseException: base class for all exceptions
  • Exception: General exception base class
  • AttributeError: Object property does not exist
  • IndexError: no such sequence index
  • I0Error: input / output operation failed
  • KeyboardInterrupt: User Interrupt Executing
  • KeyError: This key does not exist map
  • NameError: Can not find the name (variable)
  • SyntaxError: Python syntax error
  • TypeError: invalid type of operation
  • ValueError: Invalid parameter passed
  • ZeroDivisionError: In addition to calculating the second parameter is 0
Exception Handling
  • try-except to catch exceptions
  • try-except grammar
try:
	raise
except Exceetion as err:
	print(err)
try:
    num1 = int(input('enter the first number:'))
    num2 = int(input('enter the second number:'))
    print(num1 / num2)#检测语句块
except ValueError:#异常类名
    print('Please input a digit!')#异常处理
  • Except clauses and a plurality of capturing a plurality of abnormality except block
try:
    num1 = int(input('enter the first number:'))
    num2 = int(input('enter the second number:'))
    print(num1 / num2)
except ValueError:
    print('Please input a digit!')
except ZeroDivisionError:
    print('The second number cannot be zero!')
try:
    num1 = int(input('enter the first number:'))
    num2 = int(input('enter the second number:'))
    print(num1 / num2)
except (ValueError,ZeroDivisionError):
    print('Please input a digit!')
  • Catch all exceptions
try:
    num1 = int(input('enter the first number:'))
    num2 = int(input('enter the second number:'))
    print(num1 / num2)
except Exception as err:
    print('Something went wrong!')
    print(err)
  • Else clause can be added
try:
    num1 = int(input('enter the first number:'))
    num2 = int(input('enter the second number:'))
    print(num1 / num2)
except Exception as err:
    print('Something went wrong!')
    print(err)
else:
    print('everything is OK!')
  • The cyclic process
while True:
    try:
        num1 = int(input('enter the first number:'))
        num2 = int(input('enter the second number:'))
        print(num1 / num2)
        break
    except Exception as err:
        print('Something went wrong!')
        print(err)
    else:
        print('everything is OK!')
  • finally clause regardless of whether an exception occurs finally clause should be executed
  • Context Manager (Context Manager) and with statement
try:
    f = open('data.txt')
    for line in f:
        print(line,end='')
except IOError:
    print('cannot open the file!')
finally:
    f.close()
#文件是否正常打开都对它进行关闭,当文件不能打开时会出错
with open('data.txt') as f:#把上下文管理表达式的值赋给变量
    for line in f:
        print(line,end='')
Published 45 original articles · won praise 2 · Views 1228

Guess you like

Origin blog.csdn.net/soulmate______/article/details/104826069