函数即变量
函数即变量:
前向引用:pythn代码从上往下执行,遇到函数会再内存中为其划分空间,并将函数作为字符串存入,但不会运行,知道函数被调用才会执行。所以几个函数之间并无先后之分,函数A后面写函数B,函数A也可以调用函数B
# 前向引用 def foo(): print('from foo') bar() def bar(): print('樱桃小丸子') foo()
递归:"问路"
递归特性:
1. 必须有明确的结束条件,return
2. 每次进入更深一层递归时,问题规模相对上次递归都应有所减少
3. 递归效率不高,递归层次过多导致栈(内存)溢出(再计算机中,函数调用时通过栈(atsck)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。)
def calc(n): print(n) calc(n) calc(10)
def calc(n):
print(n)
if int(n/2)==0:
return n
res=calc(int(n/2))==0
return res
calc(10)
person_list=('张三','李四','王五','蒋六','赵七') def ask_way(person_list): if len(person_list)==0: return '这些人都不知道' person=person_list.pop(0) if person=='张三': return '楼下超市就有卖吃的,但是没有生活用品' print('Hi,%s 你知道哪里有卖吃的吗?' % person) print('%回答道:我不知道,但是我可以帮你问一下 ' %(person,person_list)) time.sleep(1) print('%s问的结果是:%res' % (person,res)) return res res=ask_way(person_list) print(res)