本節介紹一些以前語法的高級使用,能夠是咱們的程序看起來更爲優雅和高效。python
若是遇到大量含有if和elif的分支判斷中,按照傳統的寫法無疑會下降程序邏輯的可讀性,此時可使用字典方式替換if else的使用。express
如下示例進行說明:安全
a = 10 b = 8 strs = input("輸入你的操做:") if strs == '+': print(a+b) elif strs == '-': print(a-b) elif strs == '*': print(a*b) else: print(a/b)
輸入你的操做:+ 18
能夠轉化爲:app
a = 10 b = 8 strs = input("輸入你的操做:") actions = {'+':a+b,'-':a-b,'*':a*b,'/':a/b} print(actions[strs])
輸入你的操做:+ 18
生成器提供了一種執行「惰性」評估的方法,意味着只有在實際須要的時候才計算值,這比一次性計算一個很大的列表要更加有效。有效的生成器能夠生成咱們所須要數量的值--而沒有上限函數
(expression for item in iterable) (expression for item in iterable if condition)
for t in (x for x in range(10) if x%2==0): print(t)
0 2 4 6 8
def getNum(num=1): num = 1 while True: yield num num +=1
getNum()
<generator object getNum at 0x00000214B6597D58>
for t in getNum(): if t > 5: break print(t)
1 2 3 4 5
def getNum1(num=1): num = 1 while True: recived = yield num if recived is None: num += 1 else: num = recived + 10
result = [] cnum = getNum1(2) while len(result)<5: x = next(cnum) if x==4: x = cnum.send(7) result.append(x)
print(result)
[1, 2, 3, 17, 18]
動態代碼執行便是讓用戶本身輸入代碼並讓Python執行,此種方法即容許Python程序執行任意代碼必然會帶來很大的安全風險,故而須要謹慎使用。ui
另外經過動態執行,能夠爲程序增長和擴展動態功能。spa
計算指定表達式的值。也就是說它要執行的python代碼只能是單個表達式(注意eval不支持任何形式的賦值操做),而不能是複雜的代碼邏輯。其語法格式以下:設計
eval(source, globals=None, locals=None)
參數說明:code
返回值:對象
eval(input('請您輸入要執行的腳本:'))
請您輸入要執行的腳本:print([x for x in range(5)]) [0, 1, 2, 3, 4]
動態執行python代碼。也就是說exec能夠執行復雜的python代碼,而不像eval函數那樣只能計算一個表達式的值。
exec(source, globals=None, locals=None)
參數說明:
__builtins__
,則系統會將當前環境中的 __builtins__
複製到本身提供的 globals 中,而後纔會進行計算;若是連 globals 這個參數都沒有被提供,則使用 Python 的全局命名空間。返回值:
import math code = """ def area_of_sphere(r): print(4*math.pi*r**2) """ context = {} context['math']=math exec(code,context)
area_of_sphere = context['area_of_sphere'] area_of_sphere(5)
314.1592653589793
globals參數便可做爲exec執行函數中須要獲取參數或模塊的來源(如:math),也能夠做爲外部想獲取exec執行函數的字典(如:area_of_sphere)
compile() 函數將一個字符串編譯爲字節代碼。其語法格式
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
參數說明:
code = """ import math def area_of_sphere(r): print(4*math.pi*r**2) """ c = compile(code,'','exec') c
<code object <module> at 0x00000214B6662C90, file "", line 2>
context = {} exec(c,context) context['area_of_sphere'](5)
314.1592653589793
exec(c) c1 = globals()['area_of_sphere'] c1(5)
314.1592653589793
更多文章,請關注: