-5

I'm trying to develop a Python 3 program that will allow the user to choose a denominator and evaluate an equation. For Example:

  • The user selects 5 to be the denominator
  • The equation will increment until the given denominator
  • (1/1) + (1/2) + (1/3) + (1/4) + (1/5)
  • The output should be (2.283333)

My code:

d = input ("Select a denominator") 
for i in range(d)
    d += (1/d)
    print(d)

So far I'm only able to ask the user for the input/denominator. I tried putting it in a loop but I am doing something wrong. This is what prints out:

5.2
5.392307
5.577757
5.757040
5.930740
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

2
final_denominator = int(input("Select a denominator: "))
total = 0
for i in range(1, final_denominator + 1):
    total += 1 / i
print(total)
  • You need to convert the inputted string to an integer with int()
  • Use a different variable for the total and the final denominator.
  • range(x) goes from 0 to x - 1, to go from 1 to x you need range(1, x + 1).
  • You need to add 1 / i rather than 1 / final_denominator to the total.

Alternatively, this is a good use for a generator expression:

final_denominator = int(input("Select a denominator: "))
total = sum(1 / i for i in range(1, final_denominator + 1))
print(total)
Jasmijn
  • 9,370
  • 2
  • 29
  • 43