0

I have converted the base program into two functions. I need to be able to exit the program by hitting the enter/return key but when I do, it throws a ValueError: could not covert string to float.

I have tried assigning the var(x) outside of the loop and also tried using an if statement to close but the issue seems to be with the float attached to the input. I'm wondering if I can move the float statement to another part of the program and still get the correct output?

import math def newton(x): tolerance = 0.000001 estimate = 1.0 while True: estimate = (estimate + x / estimate) / 2 difference = abs(x - estimate ** 2) if difference <= tolerance: break return estimate

def main():

while True:
    x = float(input("Enter a positive number or enter/return to quit: "))
    print("The program's estimate is", newton(x))
    print("Python's estimate is     ", math.sqrt(x))

if name == 'main': main()

My expectation is that when the user hits the enter key, the program will end with no errors. The float is needed for the program.

File "C:/Users/travisja/.PyCharmCE2019.2/config/scratches/scratch.py", line 13, in main x = float(input("Enter a positive number or enter/return to quit: ")) ValueError: could not convert string to float:

4

1 回答 1

0

您收到错误是因为它试图将在点击Enter(空字符串)时收到的输入转换为float. 空字符串无法转换为浮点数,因此出现错误。

不过,您可以轻松地重新构建代码结构:

import math

# Prompt the user for a number first time
input_val = input("Enter a positive number or enter/return to quit: ")

# Continue until user hits Enter
while input_val:
    try:
        x = float(input_val)
        print("The program's estimate is", newton(x))
        print("Python's estimate is     ", math.sqrt(x))

    # Catch if we try to calculate newton or sqrt on a negative number or string
    except ValueError:
        print(f"Input {input_val} is not a valid number")

    finally:
        input_val = input("Enter a positive number or enter/return to quit: ")
于 2019-09-17T16:48:01.163 回答