内置函数,内置函数就是python自己定义好的,咱们直接拿来就能够用的函数。(python中一共有68中内置函数。)html
|
下面咱们由做用不一样分别进行详述:(字体加粗的为重点要掌握的)python
与做用域相关:global和localshell
str类型代码的执行:eval、exec、compile缓存
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec') >>> exec (compile1) 1
3
5
7
9
>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval') >>> eval(compile2) >>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single') >>> name #执行前name变量不存在
Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> name NameError: name 'name' is not defined >>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"
与数字相关的:数据结构
print(divmod(7,3))#(2,1)
print(round(3.14159,2))#3.14
f = 4.197937590783291932703479 #-->二进制转换的问题
print(f)#4.197937590783292
与数据结构有关:ide
chr(97)
返回字符串'a'
,同时 chr(8364)
返回字符串'€'
),ascii,reprl2 = [1,3,5,-2,-4,-6] print(sorted(l2,key=abs,reverse=True))#[-6, 5, -4, 3, -2, 1]
print(sorted(l2))#[-6, -4, -2, 1, 3, 5]
print(l2)#[1, 3, 5, -2, -4, -6]
l = ['a','b'] for i,j in enumerate(l,1): print(i,j) #1 a
2 b L = [1,2,3,4] def pow2(x): return x*x l=map(pow2,L) print(list(l)) # 结果:
[1, 4, 9, 16] def is_odd(x): return x % 2 == 1 l=filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) print(list(l)) # 结果:
[1, 7, 9, 17]
其余:函数
输入输出:input(),print()源码分析
#print的源码分析:
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
""" print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) file: 默认是输出到屏幕,若是设置为文件句柄,输出到文件 sep: 打印多个值之间的分隔符,默认为空格 end: 每一次打印的结尾,默认为换行符 flush: 当即把内容输出到流文件,不做缓存 """
#有关进度条打印的小知识
import time import sys for i in range(0,101,2): time.sleep(0.1) char_num = i//2 #打印多少个#
per_str = '%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num) print(per_str,end='', file=sys.stdout, flush=True) 复制代码
def func():pass
print(callable(func)) #参数是函数名,可调用,返回True
print(callable(123)) #参数是数字,不可调用,返回False
附:可供参考的有关全部内置函数的文档https://docs.python.org/3/library/functions.html#object字体