python recursion and built-in method

Recursive: function calls itself

Core: progressive time to achieve a result, more and more small-scale problems (not necessarily true reach); set a condition that allows the end of the last function call

Exercise:

The first person's name is 16 years old, everyone behind older than 2 years before a large, seeking a sixth person's age

age = 16
def age_func(x):
    global age # 设置为全局变量
    if x == 0:#递归的终止条件
        return age
    return age_func(x - 1) + 2

age_func(5)

'''
age_func(5)    return age_func(4) + 2
age_func(4)    return age_func(3) + 2 
age_func(3)    return age_func(2) + 2 
age_func(2)    return age_func(1) + 2 
age_func(1)    return age_func(0) + 2 
age_func(0)    teturn 16

再往回退

age_func(1)    return 18
age_func(2)    return 20
age_func(3)    return 22
age_func(4)    return 24
age_func(5)    return 26

完毕
'''

Common built-in method

# bytes():解码字符
res = '你好'.encode('utf8')
print(res) #b'\xe4\xbd\xa0\xe5\xa5\xbd'

res = bytes('你好',encoding='utf8')
print(res) #b'\xe4\xbd\xa0\xe5\xa5\xbd'


# chr()/ord():数字转字符/字符转数字
print(chr(65)) #A
print(ord('A')) #65

# divmod():分栏(取整和取余)
print(divmod(10, 3)) #(3, 1)


# enumerate():带有索引的迭代
l = ['a', 'b', 'c']
for i in enumerate(l):
    print(i)
 '''
(0, 'a')
(1, 'b')
(2, 'c')
 '''


# eval():把字符串翻译成数据类型,并执行里面的运算
lis = '[1, 2, 3]'
lis_eval = eval(lis)
print(lis_eval) #[1, 2, 3]

Guess you like

Origin www.cnblogs.com/michealjy/p/11352415.html