Home > database >  How can I write a program that displays the value of e 2.71828
How can I write a program that displays the value of e 2.71828

Time:02-20

How can I write a program that displays the value of e 2.71828 in the following format? I know that I have to use loops. (python) I have to use arrays.

#2.7
#2.71
#2.718
#2.7182
#2.71828

We are given with

e="2."
decimal=[7,1,8,2,8]

CodePudding user response:

A naive approach if the decimal is int:

e="2."
decimal=[7,1,8,2,8]


for i in range(1,len(decimal)):
    x=e
    for j in decimal[:i] :   
        x  = str(j)
    print(x)

a little bit cleaner

e="2."
decimal=[7,1,8,2,8]
decimal = [str(i) for i in decimal]     

for i in range(1,len(decimal)):
    print(e ''.join(decimal[:i])) 

CodePudding user response:

Another way you can accomplish this is with the itertools library:

import itertools

e="2."
decimal=[7,1,8,2,8]

l = itertools.accumulate([e]   list(map(str,decimal)))
for elem in list(l)[1:]:
    print(elem)

Output:

2.7
2.71
2.718
2.7182
2.71828

CodePudding user response:

e="2."
decimal=[7,1,8,2,8]

for d in decimal:
    e  = str(d)

print(e)
  • Related