字符串类型代码执行:
exec('print(123)')
eval('print(123)')
print(eval('1*2+3+4')) # 有返回值
print(exec('1+2+3+4')) #没有返回值
# exec和eval都可以执行 字符串类型的代码
# eval有返回值 —— 有结果的简单计算
# exec没有返回值 —— 简单流程控制
# eval只能用在你明确知道你要执行的代码是什么
code = '''for i in range(10):
print(i*'*')
'''
exec(code)
code1 = 'for i in range(0,10): print (i)'
compile1 = compile(code1,'','exec')
exec(compile1) code2 = '1 + 2 + 3 + 4'
compile2 = compile(code2,'','eval')
print(eval(compile2))
code3 = 'name = input("please input your name:")'
compile3 = compile(code3,'','single')
exec(compile3) #执行时显示交互命令,提示输入
print(name)
# name #执行后name变量有值
# "'pythoner'"
Eva_J
内置函数——eval、exec、compile
eval() 将字符串类型的代码执行并返回结果
print(eval('1+2+3+4'))
exec()将自字符串类型的代码执行
print(exec("1+2+3+4"))
exec("print('hello,world')")

code = '''
import os
print(os.path.abspath('.'))
'''
code = '''
print(123)
a = 20
print(a)
'''
a = 10
exec(code,{'print':print},)
print(a)

compile 将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。
参数说明:
1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。
2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。
3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1) >>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2) >>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"

# 复数 —— complex
# 实数 : 有理数
# 无理数
# 虚数 :虚无缥缈的数
# 5 + 12j === 复合的数 === 复数
# 6 + 15j
浮点数:
# 浮点数(有限循环小数,无限循环小数) != 小数 :有限循环小数,无限循环小数,无限不循环小数
# 浮点数
#354.123 = 3.54123*10**2 = 35.4123 * 10
# f = 1.781326913750135970
# print(f)
进制转换:
print(bin(10))
print(oct(10))
print(hex(10)) # 0b1010
# 0o12
# 0xa
print(abs(-5))
print(abs(5)) #求绝对值
print(divmod(7,2)) # div除法 mod取余 (3, 1)
print(divmod(9,5)) # 除余 (1, 4)
print(round(3.14159,3)) #保留小数位数
print(pow(2,3)) #pow幂运算 == 2**3 8
print(pow(3,2)) #
print(pow(2,3,3)) #幂运算之后再取余 2
print(pow(3,2,1)) #
sum:
sum(iterable, start)
iterable start 只能通过位置传参,不允许关键字传参
ret = sum([1,2,3,4,5,6])
print(ret)
ret = sum([1,2,3,4,5,6,10],10)
print(ret) ret = sum([1,2,3,4,5,6,10],)
print(ret)
min max:
print(min([1,2,3,4])) #
print(min(1,2,3,4)) #
print(min(1,2,3,-4)) #-4
print(min(1,2,3,-4,key = abs)) #1 变为绝对值后求最小值 print(max([1,2,3,4])) #
print(max(1,2,3,4)) #
print(max(1,2,3,-4)) #
print(max(1,2,3,-4,key = abs)) #-4 变为绝对值后求最大值