如何使用回车键退出"While True" |抛出值错误无法将 str 转换为 float

How to exit "While True" with enter key | Throws Value Error can't convert str to float

我已经将基本程序转换为两个函数。我需要能够通过按下 enter/return 键来退出程序,但是当我这样做时,它会抛出一个 ValueError: could not covert string to float.

我试过在循环外分配 var(x),也试过使用 if 语句来关闭,但问题似乎与附加到输入的浮点数有关。我想知道我是否可以将 float 语句移动到程序的另一部分并仍然得到正确的输出?

导入数学 定义牛顿(x): 公差 = 0.000001 估计 = 1.0 而真实的: 估计 = (估计 + x / 估计) / 2 差异 = abs(x - 估计 ** 2) 如果差异 <= 公差: 休息 return估计

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': 主()

我的期望是,当用户按下回车键时,程序将无错误地结束。程序需要浮点数。

文件 "C:/Users/travisja/.PyCharmCE2019.2/config/scratches/scratch.py",第 13 行,在 main 中 x = 浮动(输入("Enter a positive number or enter/return to quit: ")) ValueError:无法将字符串转换为浮点数:

您收到错误是因为它试图将仅点击 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: ")