Structure of Repetition in Python

Asked

Viewed 523 times

-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)
  • Adjusting the question to be impersonal and can help other people in the future as well.

  • Can you ask the question at least one of your attempts? It will be easier to identify your difficulty.

  • All right, just a second.

  • 1

    @What then? She gave up the question?

  • @Andersoncarloswoss Sorry, I thought I edited and it wasn’t, now I edited.

  • I disagree with the closure of this question. The first version of it was in fact not very good, but currently there is nothing wrong with it. I voted to reopen.

Show 1 more comment

1 answer

1


In python, the break does not terminate the loop, but interrupts it immediately. Unlike other languages, you do not have a keyword like fim-while or similar. The compiler/interpreter knows where the while ends looking at the identation.

Also, you had forgotten to increase the values i and j.

Another mistake was that the e = e + 1/ fat should be after the while internal, and not within it.

Another detail is that you are reading is a value N, and not a value B.

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

Here’s what your code looks like 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 report 25 as the value of N, this is the way out:

Valor de E = 2.7182818284590455

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.