Search code examples
pythonmathwhile-loopuser-inputbreak

Natural logarithm using while loop in Python


The function: y(x) = ln 1/(1-x)

How do I write a Python program to evaluate the above function for any user-specified value of x, where ln is the natural logarithm (logarithm to the base e)? I am to compulsorily use a while loop so that the program repeats the calculation for each legal value of x entered into the program. When an illegal value of "x" is entered, I used break to terminate the program.

I have tried using the following code but it seems not to run appropriately:

import math

n = int(input("Enter the number to be converted: "))

while n >= 0:
    if n <= 0:    
        break

print("Your number is not positive terminating program.") 
    
x = math.log(n) * 1/(1-n)

print("The Log Value is:", x)

Solution

  • Try:

    import math
    
    while True: # infinite loop, to be halted by break
        x = float(input('Enter the number to be converted: ')) # get the input
        if x >= 1: # is the input legal?
            print('The function cannot be evaluated at x >= 1.')
            break # break out of the loop if the input is "illegal"
        y = math.log(1 / (1 - x))
        print('The log value is:', y)
    
    1. First, your program might fall into an infinite loop; if you enter n = 1 for example, then n >= 0 is true and n <= 0 is false, so your program runs the while loop indefinitely.

    2. A "legal input" to the function must be a (real) number (strictly) less than 1. If n == 1, then you are doing division by zero. If n > 1, then you are entering a negative number into the log function.

    In the suggested code, I am checking only the "numerical legality" of the input; i.e., entering an empty string would throw an error. But I think that is beyond what you are asked for in the assignment.