English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Python advanced knowledge

Python reference manual

Python program uses anonymous functions to calculate2power

Python instance大全

In this program, you will learn to use Python anonymous functions to display integers2power.

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 find2power.

Source code

# Use anonymous function to display2power
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", power equals, result[i])

Output result

Total number of items: 10
2of 0 power equals 1
2of 1 power equals 2
2of 2 power equals 4
2of 3 power equals 8
2of 4 power equals 16
2of 5 power equals 32
2of 6 power equals 64
2of 7 power equals 128
2of 8 power equals 256
2of 9 power equals 512

Note:To test different numbers of items, please change the value of the 'terms' variable.

Python instance大全