[day 27 of getting started with python] python function - built-in function

Posted by netpumber on Mon, 21 Feb 2022 14:44:34 +0100

Built in function

Some functions have been used before. Some people will ask why I can use them directly without importing this function?
Because these functions are defined in a module called builtins, which is automatically imported when the Python environment is started by default, you can use these functions directly.
We can output in IDLE

globals()
{'__name__':'__main__','__doc__':None,'__package__':None,'__loader__'<class'_frozen_importlib.BuiltinImporter'>,'__spec__':None,'__annotations__'{},'__builtins__':<module'builtins'(built-in)>}
dir(__builtins__)
['ArithmeticError','AssertionError','AttributeError','BaseException','BlockingIOError','BrokenPipeError','BufferError','BytesWarning','ChildProcessError','ConnectionAbortedError','ConnectionError','ConnectionRefusedError','ConnectionResetError','DeprecationWarning','EOFError','Ellipsis','EnvironmentError','Exception','False','FileExistsError','FileNotFoundError','FloatingPointError','FutureWarning','GeneratorExit','IOError','ImportError','ImportWarning','IndentationError','IndexError','InterruptedError','IsADirectoryError','KeyError','KeyboardInterrupt','LookupError','MemoryError','ModuleNotFoundError','NameError','None','NotADirectoryError','NotImplemented','NotImplementedError','OSError','OverflowError','PendingDeprecationWarning','PermissionError','ProcessLookupError','RecursionError','ReferenceError','ResourceWarning','RuntimeError','RuntimeWarning','StopAsyncIteration','StopIteration','SyntaxError','SyntaxWarning','SystemError','SystemExit','TabError','TimeoutError','True','TypeError','UnboundLocalError','UnicodeDecodeError','UnicodeEncodeError','UnicodeError','UnicodeTranslateError','UnicodeWarning','UserWarning','ValueError','Warning','WindowsError','ZeroDivisionError','_','__build_class__','__debug__','__doc__','__import__','__loader__','__name__','__package__','__spec__','abs','all','any','ascii','bin','bool','bytearray','bytes','callable','chr','classmethod','compile','complex','copyright','credits','delattr','dict','dir','divmod','enumerate','eval','exec','exit','filter','float','format','frozenset','getattr','globals','hasattr','hash','help','hex','id','input','int','isinstance','issubclass','iter','len','license','list','locals','map','max','memoryview','min','next','object','oct','open','ord','pow','print','property','quit','range','repr','reversed','round','set','setattr','slice','sorted','staticmethod','str','sum','super','tuple','type','vars','zip']

There are nearly 80 built-in functions, more than 60 built-in exceptions, several built-in constants, special names and module related attributes in the builtins module.
Next, let's introduce some built-in functions commonly used in work:\

abs()

Absolute value function. For example, abs(-1)=1

abs(-10)
10
f = abs
f(-1)
1
abs=id
abs(1)
18322788382

Take the abs() function as an example to show two features. First, built-in functions can be assigned to other variables, and other objects can also be assigned to built-in functions. At this time, it completely changes. Therefore, built-in functions are not Python keywords. Pay attention to their protection. Do not use variable names with the same names as built-in functions, which will confuse the code and prone to errors that are difficult to check.

all()

Receive an iteratable object. If the bool operation value of all elements in the object is True, it returns True; otherwise, it returns False

all([1,1,1])
True
all([1,1,0])
False

any()

Receive an iteratable object. If the bool operation value of an element in the iterated object is True, it returns True; otherwise, it returns False. And all() are brothers.

any([0,0,1])
True
any([0,0,0])
False

bin(),oct(),hex()

The three functions convert decimal numbers to 2 / 8 / hexadecimal respectively.

i =10
bin(i)
'0b1010'	 #0b indicates binary
oct(i)
'0o12'		 #0o indicates octal
hex(i)
'0xa'			 #0x indicates hexadecimal

bool()

Tests whether the execution result of an object or expression is True or False.

bool(1==2)
False
bool(abs(-1))
True
bool(None)
False

bytes()

Converts an object to a byte type. For example: S = 'Zhang San'; m = bytes (s, encoding=‘utf-8’)

i=2
bytes(i)
b'\x00\x00'
s ='haha'
bytes(s)
Traceback(most recent call last):	
	File"<pyshell#24>",line 1,in <module>				
	    bytes(s)
TypeError:string argument without an encoding
bytes(s,encoding="utf-8")
b'haha'
bytes(s,encoding="GBK")
b'haha'
s ="python"
s.encode()		#Convert string to bytes

str()

To convert an object to a string type, you can also specify the encoding method. For example: str(bytes object, encoding = 'utf-8')

i =2
str(i)
'2'
b =b"haha"
str(b)				#be careful!
"b'haha'"
str(b,encoding="gb2312")
'haha'
str([1,2,3,])
'[1,2,3]'
b =b'python'
b.decode()		#Convert bytes to str

For the conversion between Bytes and string, the encode() and decode() methods are more used.

chr()

Returns the ASCII character corresponding to a decimal number, for example: chr(99) = 'c'. It can cooperate with random RandInt (65,90) random method generates random characters for the production of random verification codes.

import random
for i in range(10):				
     a =random.randint(65,90)	#65-90 is A-Z in ASCII table				        
     c =chr(a)				
     print(c,end='')
print('')

ord()

In contrast to chr(), it returns the decimal number corresponding to an ASCII character, for example, ord('A ') = 65

ord("A")
65
ord("\n")
10

compile()

Compile strings into code that Python can recognize or execute

s ="print('hello world')"
r =compile(s,"<string>","exec")
r
<code object <module> at 0x000001B23E6BE660,file"<string>",line 1>
r()
Traceback(most recent call last):		
     File"<pyshell#14>",line 1,in <module>
     		r()
TypeError:'code' object is not callable
exec(r)			#exec is required for execution
hello world
eval(r)			#eval can also
hello world

complex()

Generate complex type objects from numbers or strings.

complex(1,2)
(1+2j)

dir()
Displays all properties and methods of the object.

dir([1,2,])
['__add__','__class__','__contains__','__delattr__','__delitem__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__gt__','__hash__','__iadd__','__imul__','__init__','__init_subclass__','__iter__','__le__','__len__','__lt__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__','__setitem__','__sizeof__','__str__','__subclasshook__','append','clear','copy','count','extend','index','insert','pop','remove','reverse','sort']

divmod()

Division, returning both quotient and remainder tuples.

divmod(10,3)
(3,1)
divmod(11,4)
(2,3)

format()

Executing format() actually calls the class to which the object belongs__ format__ method.

format("200211")
'200211'
format([1,2,3])
'[1,2,3]'

globals()

Lists all global variables in the current environment. Pay attention to distinguish it from global keyword!

hash()

A function that generates hash values for immutable objects, such as strings!

hash("i am  jack")
5602200374213231465
hash(1)
1
hash(100000)
100000
hash([1,2,3,])
Traceback(most recent call last):		
    File "<pyshell#4>",	line 1,in <module>				      
         hash([1,2,3,])
TypeError:unhashable type: 'list' 
hash((1,2,3))
2528502973977326415

id()

Return the memory address of the object, which is often used to check the change of variable reference, whether the object is the same, etc. One of the common functions!

id(0)
1456845856
id(True)
1456365792
a ="Python"
id(a)
37116704

iter()

Make an iterator with the next() capability.

lis =[1,2,3]
next(lis)
Traceback(most recent call last):		
     File "<pyshell#8>",line 1,in <module>				    
          next(lis)
TypeError:'list' object is not an iterator
i =iter(lis)
i
<list_iterator object at 0x0000000002B4A128>
next(i)
1

len()

Returns the length of the object. Can no longer be one of the commonly used functions.

max min

Returns the largest or smallest element in a given set. You can specify the sorting method!

lis =['abcaaaa','abcd','abcde']
max(lis)
Specifies to return by length
max(lis,key=len)

next()

By calling the iterator__ next__ () method to get the next element.

open()

Method to open the file. In Python 2, there is also a file() method, which is abandoned in Python 3.

pow()

Power function.

>>>	pow(3,2)
9

reversed()

Reverse object

>>>	reversed					#reversed itself is a class
<class 'reversed'>
>>>	reversed([1,2,3,4,5])	#Get a list inverter < list_ reverseiterator object at 0x0000022E322B5128>
>>>	a =reversed([1,2,3,4,5])
>>>	a
<list_reverseiterator object at 0x0000022E32359668>
>>>	list(a)			#Use the list method to convert it to a list
[5,4,3,2,1]

round()

Round off

round(1.5)
2
round(1.4)
1

sum()

Seek peace

>>>	sum(1,2,3)			#An iteratable object Traceback(most recent call last) needs to be passed in:		
File "<pyshell#15>",line 1,in <module>				
     sum(1,2,3)
TypeError:sum expected at most 2 arguments,got 3
>>>	sum([1,2,3])  #Pass in a list
6
>>>	sum({1:1,2:2})	#Sudden whim, death, into a dictionary
3

type()

Displays the data type to which the object belongs. Common methods! As shown earlier.

filter()

Filter, similar to map. Set the filter conditions in the function, loop the elements in the object one by one, and leave the elements when the return value is True
(note that the return value is not left!), Form an iterator of type filter.

def f1(x):				
       if x > 3:
       			return True				
       else:								
                return False
 li =[1,2,3,4,5]
 data =filter(f1,li)
 print(type(data))
 print(list(data))
 Operation results:
 <class 'filter'>
 [4,5]

zip()

Group objects. Pair objects one by one.

list_1 =[1,2,3]
list_2 =['a','b','c']
s =zip(list_1,list_2)
print(list(s))
Operation results:
[(1,'a'),(2,'b'),(3,'c')]

Combine 3 objects:

list_1 =[1,2,3,4]
list_2 =['a','b','c',"d"]
list_3 =['aa','bb','cc',"dd"]
s =zip(list_1,list_2,list_3)
print(list(s))
Operation results:
[(1,'a','aa'),(2,'b','bb'),(3,'c','cc'),(4,'d','dd')]

What if the length of the object is inconsistent? The surplus will be abandoned! Based on the shortest!

list_1 =[1,2,3]
list_2 =['a','b','c',"d"]
s =zip(list_1,list_2)
print(list(s))
Operation results:
[(1,'a'),(2,'b'),(3,'c')]

sorted()

Sorting method. There are two important parameters: key and reverse.
Basic usage: sort the sequence directly

>>>	sorted([36,5,-12,9,-21])
[-21,-12,5,9,36]

Specifies the keyword to sort. Keyword must be a callable object. For example, in the following example, the rule is that whoever has a large absolute value will be ranked behind.

>>>	sorted([36,5,-12,9,-21],key=abs)
[5,9,-12,-21,36]

Specifies to arrange in reverse order. The following examples are sorted first in alphabetical order ignoring case, and then in reverse order.

>>>	sorted(['bob','about','Zoo','Credit'],key=str.lower,	reverse=True)
['Zoo','Credit','bob','about']

Topics: Python Back-end