Tässä ohjelmassa opit näyttämään kokonaisluvun 2 tehot Python-nimettömällä toiminnolla.
Tämän esimerkin ymmärtämiseksi sinulla on oltava tieto seuraavista Python-ohjelmointiaiheista:
- Python for Loop
- Python Anonymous / Lambda -toiminto
Alla olevassa ohjelmassa olemme käyttäneet anonyymia (lambda) toimintoa map()
sisäänrakennetun toiminnon sisällä 2: n voimien löytämiseksi.
Lähdekoodi
# Display the powers of 2 using anonymous function terms = 10 # Uncomment code below to take input from the user # terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms are:",terms) for i in range(terms): print("2 raised to power",i,"is",result(i))
Tuotos
Ehdot ovat: 10 2 nostettu tehoon 0 on 1 2 nostettu tehoon 1 on 2 2 nostettu tehoon 2 on 4 2 nostettu tehoon 3 on 8 2 nostettu tehoon 4 on 16 2 nostettu tehoon 5 on 32 2 nostettu tehoon 6 on 64 2 nostettu tehoon 7 on 128 2 nostettu tehoon 8 on 256 2 nostettu tehoon 9 on 512
Huomaa: Jos haluat testata eri termien määrää, muuta terms
muuttujan arvoa .