python基础-内置函数(1)
python 提供了很多的内置函数。
一、数值处理相关函数:
1、取绝对值:abs()
def abs(*args, **kwargs): # real signature unknown """ Return the absolute value of the argument. """ pass
2、转二进制:bin()
def bin(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ Return the binary representation of an integer. >>> bin(2796202) '0b1010101010101010101010' """
3、转八进制:oct()
def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ Return the octal representation of an integer. >>> oct(342391) '0o1234567' """
4、转十六进制:hex()
def hex(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ Return the hexadecimal representation of an integer. >>> hex(12648430) '0xc0ffee' """
5、取最大值:max()
def max(*args, key=None): # known special case of max """ max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The 使用一个可迭代的参数,返回其中最大值的项 default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument. """
6、取最小值:min()
def min(*args, key=None): # known special case of min """ min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument. """
7、浮点函数和整型函数:float(),int()
s='11.3432' #字符串 s1=int(float(s)) #先把字符串转成浮点型,然后再转为整型 print(s1)
结果: 11
8、求和函数:sum()
s=[11,22,33,44,5] print(sum(s))
9、指数函数:pow()
s=pow(2,10) print(s)
结果:1024
10、四舍五入函数:round()
r=round(1.8) print(r)
11、排序:sorted()
li=[11,2,3,44,5] r=sorted(li) print(r)
结果:[2, 3, 5, 11, 44]
二、返回是布尔值的函数:
1、所有元素为真,函数返回真:all()
def all(*args, **kwargs): # real signature unknown """ Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. """
2、有一个元素为真,函数返回真:any()
def any(*args, **kwargs): # real signature unknown """ Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. """
3、返回对象是否可调用:callable()
def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__ """ Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances of classes with a __call__() method. """
4、判断对象是否是指定类的实例:isinstance()
s = ['Spring', 'Summer', 'Fall', 'Winter'] print(isinstance(s,list))
三、编译和执行代码
1、把字符串编译成python代码:compile()
s="print(123)" r=compile(s,'<string>',"exec") exec(r)
2、执行代码:exec() 和 eval()
两者区别:a、exec()可以执行python 代码,也可以执行表达式,而eval() 只能执行表达式
b、exec()只是执行,没有返回值,而eval() 有返回值
s="print(123)" r=compile(s,'<string>',"exec") exec(r) exec("print('10*10')") r=eval("8*8") print(r)