English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use Python anonymous functions to display integers2to the power
To understand this example, you should understand the followingPython programmingTopic:
In the following program, we use an anonymous (lambda) function inside the map() built-in function to find2to the power
# Use anonymous function to display2to the power terms = 10 # The following code is commented out to accept user input # terms = int(input("How many items? ")) # Use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) print("Total number of items:", terms) for i in range(terms): print("2of "i", "to the power of", result[i])
Output result
Total number of items: 10 2of 0 to the power of 1 2of 1 to the power of 2 2of 2 to the power of 4 2of 3 to the power of 8 2of 4 to the power of 16 2of 5 to the power of 32 2of 6 to the power of 64 2of 7 to the power of 128 2of 8 to the power of 256 2of 9 to the power of 512
Note:To test different numbers of items, please change the value of the terms variable.