deffib(n):if n ==0or n ==1:return n
else:return fib(n -1)+ fib(n -2)
defhanoi(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时
deffoo(num,base):if num >= base:
foo(num // base, base)print(num % base, end =' ')
foo(126,2)1111110
变量作用域
全局变量
在程序代码主体部分的是全局变量
全局变量和局部变量用同一个名字,遵循内层屏蔽外层原则
对于一个全局变量修改它的值不能在函数中进行
a =3deff():
a =5print(a **2)25
global语句强调全局变量
deff(x):global a
print(a)
a =5print(a + x)
a =3
f(8)print(a)3135
局部变量
在函数中的变量是局部变量
异常
BaseException:所有异常的基类
Exception:常规异常的基类
AttributeError:对象不存在此属性
IndexError:序列中无此索引
I0Error:输入/输出操作失败
KeyboardInterrupt:用户中断执行
KeyError:映射中不存在此键
NameError:找不到名字(变量)
SyntaxError:Python 语法错误
TypeError:对类型无效的操作
ValueError:传入无效的参数
ZeroDivisionError:除运算的第二个参数为0
异常处理
try-except捕捉异常
try-except语法
try:raiseexcept 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子句和一个except块捕捉多个异常
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!')
捕捉所有异常
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子句
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!')
利用循环处理
whileTrue:try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)breakexcept Exception as err:print('Something went wrong!')print(err)else:print('everything is OK!')
finally子句不管是否发生异常finally子句都要被执行
上下文管理器(Context Manager)和with语句
try:
f =open('data.txt')for line in f:print(line,end='')except IOError:print('cannot open the file!')finally:
f.close()#文件是否正常打开都对它进行关闭,当文件不能打开时会出错
withopen('data.txt')as f:#把上下文管理表达式的值赋给变量for line in f:print(line,end='')