Python Basics: 68 Python Built-in Functions Explained

Built-in functions are functions provided by Python for you to use directly, such as print., input, etc. As of python version 3.6.2, python provides a total of 68 built-in functions, as follows

abs()           dict()        help()         min()         setattr()
all()           dir()         hex()          next()        slice() 
any()           divmod()      id()           object()      sorted() 
ascii()         enumerate()   input()        oct()         staticmethod() 
bin()           eval()        int()          open()        str() 
bool()          exec()        isinstance()   ord()         sum() 
bytearray()     filter()       issubclass()   pow()         super() 
bytes()         float()        iter()         print()       tuple() 
callable()      format()      len()          property()    type() 
chr()           frozenset()   list()         range()       vars() 
classmethod()   getattr()     locals()       repr()        zip() 
compile()       globals()     map()          reversed()    __import__() 
complex()       hasattr()     max()          round() 
delattr()       hash()        memoryview()   set()

This article comprehensively organizes these 68 built-in functions into 12 categories. Readers who are learning the basics of Python must not miss it. It is recommended to collect and learn!

   digital correlation

1. Data Type

  • bool : Boolean (True, False)

  • int : integer (integer)

  • float : float (decimal)

  • complex : plural

2. Base conversion

  • bin() converts the given arguments to binary

  • otc() converts the given argument to octal

  • hex() converts the given argument to hexadecimal

print(bin(10))  # 二进制:0b1010
print(hex(10))  # 十六进制:0xa
print(oct(10))  # 八进制:0o12

3. Mathematical operations

  • abs() returns absolute value

  • divmode() returns the quotient and remainder

  • round() rounds

  • pow(a, b) Find the b power of a, if there are three parameters. After the power is calculated, take the remainder of the third number

  • sum() summation

  • min() find the minimum value

  • max() find the maximum value

print(abs(-2))  # 绝对值:2
print(divmod(20,3)) # 求商和余数:(6,2)
print(round(4.50))   # 五舍六入:4
print(round(4.51))   #5
print(pow(10,2,3))  # 如果给了第三个参数. 表示最后取余:1
print(sum([1,2,3,4,5,6,7,8,9,10]))  # 求和:55
print(min(5,3,9,12,7,2))  #求最小值:2
print(max(7,3,15,9,4,13))  #求最大值:15

   data structure related

1. Sequence

(1) Lists and tuples

  • list() converts an iterable object to a list

  • tuple() converts an iterable to a tuple

print(list((1,2,3,4,5,6)))  #[1, 2, 3, 4, 5, 6]
print(tuple([1,2,3,4,5,6]))  #(1, 2, 3, 4, 5, 6)

(2) Related built-in functions

  • reversed() reverses a sequence, returning an iterator of the reversed sequence

  • slice() slice of list

lst = "你好啊"
it = reversed(lst)   # 不会改变原列表. 返回一个迭代器, 设计上的一个规则
print(list(it))  #['啊', '好', '你']
lst = [1, 2, 3, 4, 5, 6, 7]
print(lst[1:3:1])  #[2,3]
s = slice(1, 3, 1)  #  切片用的
print(lst[s])  #[2,3]

(3) String

  • str() converts data to string

print(str(123)+'456')  #123456
  format()     与具体数据相关, 用于计算各种小数, 精算等.
s = "hello world!"
print(format(s, "^20"))  #剧中
print(format(s, "<20"))  #左对齐
print(format(s, ">20"))  #右对齐
#     hello world!    
# hello world!        
#         hello world!
print(format(3, 'b' ))    # 二进制:11
print(format(97, 'c' ))   # 转换成unicode字符:a
print(format(11, 'd' ))   # ⼗进制:11
print(format(11, 'o' ))   # 八进制:13 
print(format(11, 'x' ))   # 十六进制(⼩写字母):b
print(format(11, 'X' ))   # 十六进制(大写字母):B
print(format(11, 'n' ))   # 和d⼀样:11
print(format(11))         # 和d⼀样:11

print(format(123456789, 'e' ))      # 科学计数法. 默认保留6位小数:1.234568e+08
print(format(123456789, '0.2e' ))   # 科学计数法. 保留2位小数(小写):1.23e+08
print(format(123456789, '0.2E' ))   # 科学计数法. 保留2位小数(大写):1.23E+08
print(format(1.23456789, 'f' ))     # 小数点计数法. 保留6位小数:1.234568
print(format(1.23456789, '0.2f' ))  # 小数点计数法. 保留2位小数:1.23
print(format(1.23456789, '0.10f'))  # 小数点计数法. 保留10位小数:1.2345678900
print(format(1.23456789e+3, 'F'))   # 小数点计数法. 很大的时候输出INF:1234.567890
  • bytes() converts string to bytes type

bs = bytes("今天吃饭了吗", encoding="utf-8")
print(bs)  #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'
   bytearray()    返回一个新字节数组. 这个数字的元素是可变的, 并且每个元素的值得范围是[0,256)

ret = bytearray("alex" ,encoding ='utf-8')
print(ret[0])  #97
print(ret)  #bytearray(b'alex')
ret[0] = 65  #把65的位置A赋值给ret[0]
print(str(ret))  #bytearray(b'Alex')
  • ord() input character to find the position with character encoding

  • chr() Enter the position number to find the corresponding character

  • ascii() is the return value in the ascii code or it returns u

print(ord('a'))  # 字母a在编码表中的码位:97
print(ord('中'))  # '中'字在编码表中的位置:20013

print(chr(65))  # 已知码位,求字符是什么:A
print(chr(19999))  #丟

for i in range(65536):  #打印出0到65535的字符
    print(chr(i), end=" ")

print(ascii("@"))  #'@'
  • repr() returns the string form of an object

s = "今天\n吃了%s顿\t饭" % 3
print(s)#今天# 吃了3顿    饭
print(repr(s))   # 原样输出,过滤掉转义字符 \n \t \r 不管百分号%
#'今天\n吃了3顿\t饭'

2. Data collection

  • Dictionary: dict creates a dictionary

  • Collections: set creates a collection

frozenset() creates a frozen set, which cannot be added or deleted.

3. Related built-in functions

  • len() returns the number of elements in an object

  • sorted() sorts iterables (lamda)

Syntax: sorted(Iterable, key=function(collation), reverse=False)

  • Iterable: Iterable object

  • key: Sorting rule (sorting function), each element in the iterable object will be passed to the parameter of this function inside sorted. Sort according to the result of the function operation

  • reverse: whether it is a reverse sequence. True: reverse sequence, False: forward sequence

lst = [5,7,6,12,1,13,9,18,5]
lst.sort()  # sort是list里面的一个方法
print(lst)  #[1, 5, 5, 6, 7, 9, 12, 13, 18]

ll = sorted(lst) # 内置函数. 返回给你一个新列表  新列表是被排序的
print(ll)  #[1, 5, 5, 6, 7, 9, 12, 13, 18]

l2 = sorted(lst,reverse=True)  #倒序
print(l2)  #[18, 13, 12, 9, 7, 6, 5, 5, 1]
#根据字符串长度给列表排序
lst = ['one', 'two', 'three', 'four', 'five', 'six']
def f(s):
    return len(s)
l1 = sorted(lst, key=f, )
print(l1)  #['one', 'two', 'six', 'four', 'five', 'three']
  • enumerate() gets the enumeration object of the collection

lst = ['one','two','three','four','five']
for index, el in enumerate(lst,1):    # 把索引和元素一起获取,索引默认从0开始. 可以更改
    print(index)
    print(el)
# 1
# one
# 2
# two
# 3
# three
# 4
# four
# 5
# five
  • all() all the iterable objects are True, the result is True

  • any() one of the iterable objects is True, the result is True

print(all([1,'hello',True,9]))  #True
print(any([0,0,0,False,1,'good']))  #True
  • The zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into a tuple, and then return a list composed of these tuples. If the number of elements in each iterator is inconsistent, the length of the list is returned same as shortest object

lst1 = [1, 2, 3, 4, 5, 6]
lst2 = ['醉乡民谣', '驴得水', '放牛班的春天', '美丽人生', '辩护人', '被嫌弃的松子的一生']
lst3 = ['美国', '中国', '法国', '意大利', '韩国', '日本']
print(zip(lst1, lst1, lst3))  #<zip object at 0x00000256CA6C7A88>
for el in zip(lst1, lst2, lst3):
    print(el)
# (1, '醉乡民谣', '美国')
# (2, '驴得水', '中国')
# (3, '放牛班的春天', '法国')
# (4, '美丽人生', '意大利')
# (5, '辩护人', '韩国')
# (6, '被嫌弃的松子的一生', '日本')
  • fiter() filter(lamda)

Syntax: fiter(function.Iterable)

function: The function used to filter. In the filter, the elements in the iterable are automatically passed to the function. Then according to the True or False returned by the function, it is judged whether to retain the data, Iterable: Iterable object

Search the top architect of the official account and reply to the "interview" in the background, and send you a surprise gift package.

def func(i):    # 判断奇数
    return i % 2 == 1
    lst = [1,2,3,4,5,6,7,8,9]
l1 = filter(func, lst)  #l1是迭代器
print(l1)  #<filter object at 0x000001CE3CA98AC8>
print(list(l1))  #[1, 3, 5, 7, 9]
  • map() will map the specified sequence column according to the provided function (lamda)

Syntax: map(function, iterable)

You can map each element in the iterable object. To execute the function separately

def f(i):    return i
lst = [1,2,3,4,5,6,7,]
it = map(f, lst) # 把可迭代对象中的每一个元素传递给前面的函数进行处理. 处理的结果会返回成迭代器print(list(it))  #[1, 2, 3, 4, 5, 6, 7]

   scope dependent

  • locals() returns names in the current scope

  • globals() returns names in the global scope

def func():
    a = 10
    print(locals())  # 当前作用域中的内容
    print(globals())  # 全局作用域中的内容
    print("今天内容很多")
func()
# {'a': 10}
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': 
# <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>, 
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' 
# (built-in)>, '__file__': 'D:/pycharm/练习/week03/new14.py', '__cached__': None,
#  'func': <function func at 0x0000026F8D6B97B8>}
# 今天内容很多

   Iterator generator related

  • range() generates data

  • The next() iterator executes down once, and the __next__() method is actually used internally to return the next item of the iterator

  • iter() gets the iterator, and the __iter__() method is actually used internally to get the iterator

for i in range(15,-1,-5):
    print(i)
# 15
# 10
# 5
# 0
lst = [1,2,3,4,5]
it = iter(lst)  #  __iter__()获得迭代器
print(it.__next__())  #1
print(next(it)) #2  __next__()  
print(next(it))  #3
print(next(it))  #4

   String type code execution

  • eval() executes the code of type string. And returns the final result

  • exec() executes code of type string

  • compile() encodes the code of type string. The code object can be executed by exec statement or evaluated by eval()

s1 = input("请输入a+b:")  #输入:8+9
print(eval(s1))  # 17 可以动态的执行代码. 代码必须有返回值
s2 = "for i in range(5): print(i)"
a = exec(s2) # exec 执行代码不返回任何内容

# 0
# 1
# 2
# 3
# 4
print(a)  #None

# 动态执行代码
exec("""
def func():
    print(" 我是周杰伦")
""" )
func()  #我是周杰伦
code1 = "for i in range(3): print(i)"
com = compile(code1, "", mode="exec")   # compile并不会执行你的代码.只是编译
exec(com)   # 执行编译的结果
# 0
# 1
# 2

code2 = "5+6+7"
com2 = compile(code2, "", mode="eval")
print(eval(com2))  # 18

code3 = "name = input('请输入你的名字:')"  #输入:hello
com3 = compile(code3, "", mode="single")
exec(com3)
print(name)  #hello

   input Output

  • print() : print output

  • input() : Get the content of user output

print("hello", "world", sep="*", end="@") # sep:打印出的内容用什么连接,end:以什么为结尾
#hello*world@

   memory related

hash() : Get the hash value of the object (int, str, bool, tuple). Hash algorithm: (1) The purpose is uniqueness (2) The dict search efficiency is very high, the hash table. It takes more time to exchange space RAM

s = 'alex'print(hash(s))  #-168324845050430382lst = [1, 2, 3, 4, 5]print(hash(lst))  #报错,列表是不可哈希的  id() :  获取到对象的内存地址s = 'alex'print(id(s))  #2278345368944

   File operation related

  • open() : used to open a file, create a file handle

f = open('file',mode='r',encoding='utf-8')
f.read()
f.close()

   module related

  • __import__() : for dynamically loading classes and functions

# 让用户输入一个要导入的模块
import os
name = input("请输入你要导入的模块:")
__import__(name)    # 可以动态导入模块

   help

  • help() : the function is used to view a detailed description of the purpose of the function or module

print(help(str))  #查看字符串的用途

   call related

  • callable() : Used to check whether an object is callable. If it returns True, the object may fail to be called, but if it returns False. The call will never succeed

a = 10
print(callable(a))  #False  变量a不能被调用
#
def f():
    print("hello")
    print(callable(f))   # True 函数是可以被调用的

   View built-in properties

  • dir() : View the built-in attributes of the object, access the __dir__() method in the object

print(dir(tuple))  #查看元组的方法

Guess you like

Origin blog.csdn.net/BYGFJ/article/details/123811213