程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python basics 011] detailed understanding of all built-in functions (Part 2)

編輯:Python

Catalog

Preface

One 、exec and eval Built in functions

️1、exec Built in functions

️2、eval Built in functions

️3、 Code practice summary exec and eval Built in functions

Two 、compile Built in functions

3、 ... and 、complex Built in functions

Four 、 bin、oct、 and hex Built in functions

5、 ... and 、abs Built in functions

6、 ... and 、divmod Built in functions

7、 ... and 、pow Built in functions

8、 ... and 、sum Built in functions

Nine 、max and min Built in functions

Conclusion


Preface

Take on the last blog , What I want to explain below is Python The remaining important built-in functions in , The more important ones will be explained in detail , Relatively simple, it will be analyzed directly in combination with the code

One 、exec and eval Built in functions

️1、exec Built in functions

python Built in functions exec Support dynamic execution python Code , Pass in exec Functional object Arguments can be strings , It can also be a bytecode object . If object If the argument is a string, it will be exec Function compile and execute , If it is a bytecode object, it will be executed directly . Usually exec coordination compile Function to use .

describe
exec Execute... Stored in a string or file Python sentence , Compared with eval,exec Can perform more complex Python Code .

grammar
Here are exec The grammar of :

exec(object[, globals[, locals]])
Parameters
object: Required parameters , Represents what needs to be specified Python Code . It has to be a string or code object . If object Is a string , The string is first parsed into a group Python sentence , And then execute ( Unless there is a syntax error ). If object It's a code object , So it's simply being executed .
globals: Optional parameters , Represents the global namespace ( Store global variables ), If provided , It must be a dictionary object
locals: Optional parameters , Represents the current local namespace ( Store local variables ), If provided , It can be any mapping object . If this parameter is ignored , Then it will take globals The same value .
Return value
exec The return value is always None.

️2、eval Built in functions

eval It can only be used when you know exactly what code you want to execute , And generally, it will not be used

describe
eval() Function to execute a string expression , And return the value of the expression .

grammar
Here are eval() The grammar of the method :

eval(expression[, globals[, locals]])
Parameters
expression -- expression .
globals -- Variable scope , Global namespace , If provided , It must be a dictionary object .
locals -- Variable scope , Local namespace , If provided , It can be any mapping object .
Return value
Returns the result of an expression evaluation .

️3、 Code practice summary exec and eval Built in functions

  1.     eval There is a return value      ————  It is suitable for simple calculation with results
  2.     exec no return value ———— Suitable for simple process control

function code

exec('print(" I am the output within the string ")')
eval('print(" I am the output within the string ")')
print(exec('1+2+3+4')) #exec no return value
print(eval('1+2+3+4')) #eval There is a return value
''' Simple process control '''
code = '''for i in range(4):
print(i*'*')
'''
exec(code)
Output results :
I am the output within the string
I am the output within the string
None
10
*
**
***

Two 、compile Built in functions

  • describe

compile() Function to compile a string into byte code .

Computers don't know print etc. , They must be compiled into bytecode so that the computer can recognize

  • grammar

Here are compile() The grammar of the method :

compile(source, filename, mode[, flags[, dont_inherit]])

  • Parameters

source -- String or AST(Abstract Syntax Trees) object ..
filename -- Code file name , Pass some recognizable values if the code is not read from the file .
mode -- Specifies the type of code to compile . Can be specified as exec, eval, single.
flags -- Variable scope , Local namespace , If provided , It can be any mapping object ..
flags and dont_inherit Is used to control the flags when compiling the source code

Code understanding :

>>> # Process statements use exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
1
3
5
7
9
>>> # The simple evaluation expression uses eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
>>> # Interactive statements use single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name # Before execution name Variable does not exist
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
name
NameError: name 'name' is not defined
>>> exec(compile3) # Display interactive commands when executing , prompt
please input your name:'pythoner'
>>> name # After execution name Variables have values
"'pythoner'"

3、 ... and 、complex Built in functions

describe
complex() Function to create a value of real + imag * j To convert a string or number to a complex number . If the first argument is a string , You do not need to specify a second parameter .

grammar
complex grammar :

class complex([real[, imag]])
Parameter description :

real -- int, long, float Or a string ;
imag -- int, long, float;
Return value
Returns a complex number .

Code understanding :

Four 、 bin、oct、 and hex Built in functions

  1. bin: Returns an integer int Or long integers long int The binary representation of .
  2. oct: Converts an integer to 8 Base string ,8 Base with  0o  As a prefix .
  3. hex: Used to convert a specified number to 16 Hexadecimal number .
print(bin(10)) # Binary system
print(oct(10)) # octal
print(hex(10)) # Hexadecimal
Output results :
0b1010
0o12
0xa

5、 ... and 、abs Built in functions

Returns the absolute value of the number

print(abs(-5))
print(abs(22))
Output results :
5
22

6、 ... and 、divmod Built in functions

Python divmod() Function takes two numeric types ( Not plural ) Parameters , Returns a tuple containing quotient and remainder (a // b, a % b).

stay python 3.x This function does not support complex numbers .

Function syntax

divmod(a, b)

Parameter description :

  • a: Numbers , Not plural .
  • b: Numbers , Not plural .

If parameters a And Parameters b Are integers. , The result returned by the function is equivalent to  (a // b, a % b).

If one of the parameters is a floating point number , The result returned by the function is equivalent to (q, a % b),q Usually math.floor(a / b), But it could be 1 , Smaller than , however q * b + a % b The value of will be very close a.

If a % b The result of the remainder of is not 0 , Then the positive and negative signs of the remainder follow the parameters b It's the same , if b Positive number , The remainder is positive , if b It's a negative number , The remainder is also negative , also 0 <= abs(a % b) < abs(b).


print(divmod(5,4))
print(divmod(4,5))
print(divmod(5,-4))
Output results :
(1, 1)
(0, 4)
(-2, -3)

7、 ... and 、pow Built in functions

pow(x,y)  Method returns xy(x Of y Power ) Value .

Built in pow() Method

grammar :

pow(x, y[, z])

Function is calculation x Of y Power , If z In existence , Then we take the model of the result , The result is equivalent to pow(x,y) %z

Be careful :

pow() Called directly through a built-in method , Built-in methods take arguments as integers , and math The module converts the parameter to float.

print(pow(2,3))
print(pow(2,3,3))
print(pow(3,2,1)) # Power operation followed by remainder
Output solution :
8
2
0

8、 ... and 、sum Built in functions

describe

sum()  Methods sum the sequence .

grammar

Here are sum() The grammar of the method :

sum(iterable[, start])

Parameters

  • iterable -- Iteratable object , Such as : list 、 Tuples 、 aggregate .
  • start -- Specify the added parameters , If this value is not set , The default is 0.

Return value

Return calculation results .

print(sum([1,2,3,4,5,6]))
print(sum([1,2,3,4,5,6],10))
Output results :
21
31

Nine 、max and min Built in functions

describe

max() /min() Method returns the maximum value of a given parameter /( minimum value ), Parameters can be sequences .


grammar

Here are max() /min() The grammar of the method :

max( x, y, z, .... )
min( x, y, z, .... )

Parameters

  • x -- Numerical expression .
  • y -- Numerical expression .
  • z -- Numerical expression .

Return value

Returns the maximum value of the given parameter / minimum value .

print(min(1,2,3,4))
print(min([1,2,3,4]))
print(min([1,2,3,-4],key=abs)) # Determine the minimum value of absolute value
Output results :
1
1
1

Conclusion

Thank you for seeing here : In an unpublished article, Lu Xun said :“ If you understand the code, you must operate it yourself, so that you can better understand and absorb .”
One last sentence : A man can succeed in anything he has unlimited enthusiasm , Let's make progress together


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved