示例:
def test_eval():
str = "print('string')"
eval(str)
a = 10
b = 20
c = eval("a+b")
print("c = {0}".format(c))
if __name__ == '__main__':
test_eval()
结果:
string
c = 30
示例:
def test_01(n):
""" 递归函数 """
print("*test01,n = ", n)
if(n == 0):
print("over...")
else:
test_01(n - 1);
print("*test01,n = ", n)
if __name__ == '__main__':
test_01(5)
结果:
*test01,n = 5
*test01,n = 4
*test01,n = 3
*test01,n = 2
*test01,n = 1
*test01,n = 0
over...
*test01,n = 0
*test01,n = 1
*test01,n = 2
*test01,n = 3
*test01,n = 4
*test01,n = 5
递归算阶乘:
def factorial(number):
""" 递归算阶乘 """
if number == 1:
return 1;
else:
return number * factorial(number - 1);
if __name__ == '__main__':
print("5! = {0}".format(factorial(5)))
结果:
5! = 120
示例:
def test_02():
""" 嵌套函数 """
print('outer running')
def inner01():
""" 只能内部可用 """
print('inner01 running')
inner01()
if __name__ == '__main__':
test_02()
结果:
outer running
inner01 running
示例:
def outer():
b = 10
def inner():
nonlocal b # 声明外部函数的局部变量
print("inner b:",b)
b = 20
inner()
print("outer b:", b)
if __name__ == '__main__':
outer()
结果:
inner b: 10
outer b: 20
测试LEGB:
str = "global"
def outer():
str = "outer"
def inner():
str = "inner"
print(str)
inner()
outer()