05python 的内置函数以及匿名函数(python函数)

内置函数

截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数。

作用域相关

print(globals())        # 返回本地作用域中的所有名字
print(locals())         # 返回全局作用域中的所有名字

注意与函数中的global、local、nonlocal 关键字的区别

 生成器迭代器相关

for i in range(10):
    print(i, end=' ')
    
>>>0 1 2 3 4 5 6 7 8 9

for i in range(1, 10, 2):
    print(i, end=' ')
    
>>>1 3 5 7 9 

 其他

 

dir()                        # pass
print(callable(func))        # callable()接受一个函数名则返回True,接收其他变量返回False,可用于判断变量是否为函数!鸡肋    
help()                       # 鸡肋
import                       # 导入模块
open()                       # 打开文件
hash()                       # 字典中的键所对应的就是hash值
------------------------------------------------
input()                      # 用于与命令行的交互
print()                      # 查看print的源码
def print(self, *args, sep=' ', end='
', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass

print(1, 2, 3, sep='|')

>>>1|2|3

f = open('file', 'w')
print('aaa', file=f)          # 打印内容到指定文件
-----------------------------------------------------------------------

eval('print(123)')
exec('print(123)')

print(eval('1+2+3+4'))          # 有返回值
print(exec('1+2+3+4'))          # 无返回值

和数字处理相关

print(round(3.1415926, 2))            # 限制小数后几位

>>>3.14

print(pow(2, 3))

>>> 8

print(pow(2, 3, 2))                    # 2的3次方 / 2 取余

>>> 0

print(sum([1, 2, 3, 4, 5]))
print(sum([1, 2, 3, 4, 5], 10))        # sum(iterator, star)    
>>> 15
25

-----------------------------------------------------------------------------------
print(min([1, 2, 3, 4, -5]))
print(min([1, 2, 3, 4, -5], key=abs))  # 还可以接收函数  

>>> -5
1

未完待续。。。

原文地址:https://www.cnblogs.com/pontoon/p/10240392.html