在該程序中,您將學習使用Python匿名函數(shù)顯示整數(shù)2的冪。
要理解此示例,您應(yīng)該了解以下Python編程主題:
在下面的程序中,我們在map()內(nèi)置函數(shù)內(nèi)部使用了一個匿名(lambda)函數(shù)來查找2的冪。
#使用匿名函數(shù)顯示2的冪 terms = 10 # 以下取消注釋代碼以接受用戶輸入 # terms = int(input("有多少項? ")) # 使用匿名函數(shù) result = list(map(lambda x: 2 ** x, range(terms))) print("總項數(shù):",terms) for i in range(terms): print("2的",i,"次方等于",result[i])
輸出結(jié)果
總項數(shù): 10 2的 0 次方等于 1 2的 1 次方等于 2 2的 2 次方等于 4 2的 3 次方等于 8 2的 4 次方等于 16 2的 5 次方等于 32 2的 6 次方等于 64 2的 7 次方等于 128 2的 8 次方等于 256 2的 9 次方等于 512
注意:要測試不同數(shù)量的項,請更改terms變量的值。