# python学习笔记2（递归、保存列表、else和with语句）

Ξ魂牵梦萦Ξ
2年前 阅读 115 点赞 3

#直接调用自己：
def func():
print('from func')
func()

func()


#间接调用自己
def foo():
print('from foo')
bar()

def bar():
print('from bar')
foo()

foo()



#递归的实现：
def age(n):
if n == 1:
return 18
return age(n-1)+2

print(age(5))

# age(5)=age(4)+2 第一次进入
# age(4)=age(3)+2 第二次进入
# age(3)=age(2)+2 第三次进入
# age(2)=age(1)+2 第四次进入
# age(1)=18 第五次进入，最后判断终止条件

# age(n)=age(n-1)+2 #n>1  递归终止条件
# age(1)=18 #n=1          等于终止条件


# 实例
l =[1, 2, [3, [4, 5, 6, [7, 8, [9, 10, [11, 12, 13, [14, 15,[16,[17,]],19]]]]]]]

def search(l):
for item in l:
if type(item) is list:
search(item)
else:
print(item)

search(l)


#汉诺塔的递归实现：
def move(n, a, buffer, c):
if(n == 1):
print(a,"->",c)
return
move(n-1, a, c, buffer)
move(1, a, buffer, c)
move(n-1, buffer, a, c)
move(3, "a", "b", "c")


import pickle
#保存列表到文件
my_list = ['a','b','c',123,3.14]
pickle_file = open('my_list.pkl',"wb")
pickle.dump(my_list,pickle_file)
pickle_file.close()

#读取文件到列表
pickle_file = open('my_list.pkl',"rb")
print(my_list2)


else和with语句

# 示例：
def showMaxFactor(num):
count = num // 2
while count > 1:
if num % count == 0:
print('%d最大的约数是%d' % (num,count))
break
count -= 1
else:
print('%d是素数！' % num)

num = int(input('请输入一个数：'))
showmaxfactur(num)

try:
print(int('123'))
except ValueError as reason:
print('出错啦：' + str(reason))
else:
print('没有任何异常！')

try:
f = open('data.txt','w')
for each_line in f:
print(each_line)
except OSError as reason:
print('出错啦：' + str(reason))
finally:
f.close()

try:
with open('data.txt','w') as f:   # with 会在适当的时候，自动关闭掉文件。
for each_line in f:
print(each_line)
except OSError as reason:
print('出错啦：' + str(reason))