Built-in functions are functions that Python gives you to use directly, such as print, input, etc.
As of Python version 3.6.2, there are 68 built-in functions available, as shown below
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()Copy the code
This article summarizes the 68 built-in functions into 12 categories, which should be included in this article if you are learning the basics of Python.
Video recommendation:Learning python is not a problem
How can college students use Python to take orders online and earn more than 10,000 yuan a month
Welcome to the Python group if you want to learn: *Click here to
-
It has to do with numbers
-
1. Data types
-
2. Base conversion
-
3. Math
-
It has to do with data structures
-
1. The sequence
-
2. Data set
-
3. Related built-in functions
-
It’s scope-dependent
-
Related to iterator generators
-
Execution of string type code
-
Input and output
-
Memory related
-
File operation correlation
-
The module related
-
To help
-
Call the relevant
-
View built-in properties
It has to do with numbers
1. Data types
- Bool: Boolean (True,False)
- Int: integer (integer)
- -Serena: Oh, I’m not going to do that.
- Complex: the plural
2. Base conversion
- Bin () converts the given argument to binary
- Otc () converts the given argument to octal
- Hex () converts the given argument to hexadecimal
Print (bin(10)) # binary :0b1010 print(hex(10)) # 0xa print(oct(10)) # octal :0o12Copy the code
3. Math
- Abs () returns the absolute value
- Divmode () returns the quotient and remainder
- Round ()
- Pow (a, b) takes a to the b, if you have three arguments. Then mod the third number after taking the power
- The sum () sum
- Min () is minimized
- Max () is the maximum
Print (round(4.50)) print(round(4.50)) print(round(4.51)) # Print (pow(10,2,3)) # Said finally take over: 1 print (sum (,2,3,4,5,6,7,8,9,10 [1])) # summation: 55 print (min (5,3,9,12,7,2) # a minimum: # 2: print (Max,3,15,9,4,13) (7) a maximum: 15Copy the code
It has to do with data structures
1. The sequence
(1) Lists and tuples
- List () converts an iterable to a list
- Tuple () converts an iterable to a tuple
Print (list (6) (a)) # [1, 2, 3, 4, 5, 6] print (tuple ([6])) # (1, 2, 3, 4, 5, 6)Copy the code
(2) Related built-in functions
- Reversed () returns an iterator that reverses a sequence
- A slice of the slice() list
LST = "hi" it = reversed(LST) # Returns an iterator, a rule in the design of the print (list (it)) # [' o ', 'good', 'you'] LST = [1, 2, 3, 4, 5, 6, 7] print (LST) [1:3:1] # [2, 3] s = slice (1, 3, Print (LST [s]) #[2,3]Copy the code
(3) String
- STR () converts the data to a string
print(str(123)+'456') #123456
Copy the code
- Format () relates to specific data and is used to calculate various decimals, actuarial, etc.
s = "hello world!" Print (format(s, ">20") print(format(s, ">20")) print(format(s, ">20")) # hello world! # hello world! Print (format(3, 'b')) # binary :11 print(format(97, 'c')) # Print (format(11, 'o')) # octal: print(format(11, 'x')) # octal: print(format(11, 'x')) # octal: print(format(11, 'x')) # octal: print(format(11, 'x')) # octal: print(format(11, 'x')) Print (format(11, 'n')) # print(format(123456789, 123456789)) 'e')) # scientific notation. + +08 print(format(123456789, '0.2e')) + +08 print(format(123456789, '0.2e')) Save 2 decimal places (uppercase):1.23E+08 print(format(1.23456789, 'f')) # decimal counting. Print (format(1.23456789, '0.2f')) print(format(1.23456789, '0.2f')) Print (format(1.23456789, '0.10f')) print(format(1.23456789, '0.10f')) Print (format(1.23456789e+3, 'F')) # Very large output INF:1234.567890Copy the code
- Bytes () converts a string to bytes
Bs = bytes(" Have you eaten today? ", encoding="utf-8") print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'Copy the code
- Bytearray () returns a new bytearray. The elements of this number are mutable, and the value range for each element is [0,256].
ret = bytearray("alex" ,encoding ='utf-8') print(ret[0]) #97 print(ret) #bytearray(b'alex') ret[0] = 65 Print (STR (ret)) #bytearray(b'Alex')Copy the code
- Ord () input character finds the position with character encoding
- CHR () enters a positional number to find the corresponding character
- ASCII () is a return in ASCII code that does not return u
Print (CHR (65)) print(CHR (19999)) print(CHR (19999)) print(CHR (19999)) print(CHR (19999)) print(CHR (19999)) print(CHR (19999)) Print (CHR (I), end=" ") print(ASCII ("@")) #'@'Copy the code
- Repr () returns a string of objects
% 3 print(s)# print(repr(s)) # print(repr(s)) # print(repr(s)) #Copy the code
2. Data set
- Dictionary: dict creates a dictionary
- Collection: set creates a collection
Frozenset () creates a frozenset that cannot be added or deleted.
3. Related built-in functions
- Len () returns the number of elements in an object
- Sorted () sorts iterable objects (lamda)
Syntax: sorted(Iterable, key= function (sort), reverse=False)
- Iterable: Iterable object
- Key: sort (sort function). Inside sorted, each element in the iterable is passed to the function’s arguments. Sort by the result of the function operation
- Reverse: Indicates whether it is a flashback. True: flashback, False: forward
LST = [5,7,6,12,1,13,9,18,5] lst.sort() print(LST) #[1, 5, 5, 6, 7, 9, 12, 13] 18] c = sorted(LST) Print (ll) #[1, 5, 5, 6, 7, 9, 12, 13, 18] 2 = sorted(LST,reverse=True) 9, 7, 6, 5, 5, 1] # according to the length of the string to the list sorted 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']Copy the code
- Enumerate () Gets the enumeration object of the collection
LST = ['one','two','three','four','five'] for index, el in enumerate(LST,1): LST = ['one','two','three','four','five'] Print (index) print(el) # 1 # one # 2 # two # 3 # three # 4 # four # 5 # fiveCopy the code
- If all() iterables are True, the result is True
- If one of the any() iterables is True, the result is True
The print (all ([1, 'hello, True, 9])) # True print (any) ([0, 0, False, 1,' good '])) # TrueCopy the code
- The zip() function takes an iterable object as an argument, packs the corresponding elements of the object into a tuple, and returns a list of those tuples. If the number of elements in each iterator is inconsistent, the length of the list is the same as that of the shortest object
Lst1 = [1, 2, 3, 4, 5, 6] lst2 = [' simple folk, 'the donkey to water', 'les choristes',' beautiful life ', 'defenders',' being abandon pine nuts life] lst3 = [' us', 'China', 'French', 'Italian', Print (zip(lst1, lst1, lst3)) #<zip object at 0x00000256CA6C7A88> for el in zip(lst1, lst2, lst3): Print (el) # (1, 'simple folk songs',' us') # (2, 'the donkey to water', 'China') # (3, "les choristes", 'French') # (4, 'life is beautiful', 'Italian') # (5, 'defenders',' Korea ') # (6, 'The Life of The Despised Matsuko ',' Japan ')Copy the code
- Fiter () filter (lambda)
Syntax: fiter(function.iterable)
Function: a function used for filtering. filter automatically passes elements from iterable to function. Function returns True or False to determine whether the data is Iterable
def func(i): LST = [1,2,3,4,5,6,7,8,9] l1 = filter(func, Print (l1) #<filter object at 0x000001CE3CA98AC8> print(list(l1)) #[1, 3, 5, 7, 9]Copy the code
- Map () maps the specified sequence column based on the provided function (lamda)
Syntax: map(function, iterable)
You can map every element in an iterable. Execute function separately
Def f(I): return I LST = [1,2,3,4,5,6,7,] it = map(f, LST) # pass each element in the iterable to the previous function for processing. Print (list(it)) #[1, 2, 3, 4, 5, 6, 7]Copy the code
It’s scope-dependent
- Locals () returns the name of the current scope
- Globals () returns the name of the global scope
Def func(): a = 10 print(locals()) print(globals()) def func(): a = 10 print(locals()) 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/practice/week03 / new14 p y', '__cached__' : None, # 'func': <function func at 0x0000026F8D6B97B8>} #Copy the code
Related to iterator generators
- Range () generates data
- The next() iterator executes down once, internally actually using the __ next__() method to return the next item of the iterator
- Iter () gets the iterator, and internally uses __ iter__() to get the iterator
for i in range(15,-1,-5): Print (I) # 15 # 10 # 5 # 0 LST it = = [1, 2, 3, 4, 5] iter (LST) # __iter__ () to obtain an iterator print (it. __next__ ()) # 1 print (next) (it) # 2 __next__() print(next(it)) #3 print(next(it)) #4Copy the code
Execution of string type code
- Eval () executes string code. And returns the final result
- Exec () executes string code
- Compile () encodes the code of the string type. Code objects can be executed by exec statements or evaluated by eval()
Print (eval(s1)) print(eval(s1)) The code must return s2 = "for I in range(5): Print (a) #None print(a) #None def func(): Code1 = "for I in range(3): print(" ") func() # code1 = "for I in range(3): Print (I)" com = compile(code1, "", mode="exec") # compile does not execute your code. Code2 = "5+6+7" code2 = "compile(code2, "", Mode ="eval") print(eval(com2)) # 18 code3 =" name = input(' please input your name :')" mode="single") exec(com3) print(name) #helloCopy the code
Input and output
- Print () : Prints the output
- Input () : Gets the output of the user
Print ("hello", "world", sep="*", end="@"Copy the code
Memory related
- Hash () : Retrieves the hash value of the object (int, STR, bool, tuple). Hash algorithm :(1) Aims to be unique (2) Dict lookup efficiency is very high, hash table. Using space for time is more memory intensive
Print (hash(LST)) = [1, 2, 3, 4, 5] print(hash(LST)) # S = 'Alex' print(id(s)) #2278345368944Copy the code
File operation correlation
- Open () : Opens a file and creates a file handle
f = open('file',mode='r',encoding='utf-8')
f.read()
f.close()
Copy the code
The module related
Import__ () : Used for dynamically loading classes and functions
Import OS name = input(" Please enter the module you want to import :") __import__(name) #Copy the code
To help
- Help () : Function to view a detailed description of the purpose of a function or module
Print (help(STR)) # print(help(STR)Copy the code
Call the relevant
- Callable () : Used to check whether an object is callable. If True, object may fail, but if False. That call will never succeed
A = 10 print(callable(a)) # def f(): print("hello") print(callable(f)Copy the code
View built-in properties
- Dir () : Views the built-in properties of the object, accessing the __dir__() method in the object
Print (dir(tuple)) #Copy the code
Many beginners are confused about what Python is, what it can do, and what path to follow when learning it. If you want to learn more about it, you are welcome to join the Python group: ** Click here, ** has a large number of dry goods (zero basic and advanced classical actual combat) to share with you, and has eight years of development senior architecture Python teacher teacher to give you free teaching, to share with you the most complete domestic high-end practical Python learning process system