Python Replay Structure [closed]

-2

I need to solve the following equation in Python

  

N is an integer and positive value. Calculate and show the value of E according to the following formula:

     

E = 1 + 1/1! + 1/2! + 1/3! + ... + 1 / N!

My attempt:

n = int(input("Digite o valor de B: "))
e = 1
i = 1
while (i <= n):
  fat = 1
  j = 1
  while (j <= i):
    fat = fat*j 
    e = e + 1/fat
    break
  break
print("Valor de E = ", e)
    
asked by anonymous 13.09.2017 / 17:00

1 answer

1

In python, break does not end the loop, but stops immediately. Unlike other languages, you do not have a keyword of type fim-while or something similar. The compiler / interpreter knows where while ends up looking at the indentation.

In addition, you had forgotten to increment the values i and j .

Another error was that e = e + 1/ fat should be after internal while , not inside it.

Another detail is what you're reading is a N value, not a B value.

And I also put a print() more to break a line before showing the output.

Here's how your code gets with these fixes:

n = int(input("Digite o valor de N: "))
e = 1
i = 1
while (i <= n):
  fat = 1
  j = 1
  while (j <= i):
    fat = fat * j
    j = j + 1
  e = e + 1 / fat
  i = i + 1
print()
print("Valor de E =", e)

When you enter 25 as the value of N , here's the output:

Valor de E = 2.7182818284590455

See here working on ideone.

    
14.09.2017 / 22:32