Python-while循环的问题

Python-while循环的问题,python,input,output,Python,Input,Output,对于我的程序,我必须输入一个正数,但如果我输入一个负数,我需要程序出错,并显示一条消息:“请使用正数,然后重试”,然后返回到输入数字的部分。它陷入了一个循环。这是我的密码: import math # Receive the input number from the user x = float(input("Enter a positive number: ")) #Initialize the tolerance and estimate tolerance = 0.000001 es

对于我的程序,我必须输入一个正数,但如果我输入一个负数,我需要程序出错,并显示一条消息:“请使用正数,然后重试”,然后返回到输入数字的部分。它陷入了一个循环。这是我的密码:

import math

# Receive the input number from the user
x = float(input("Enter a positive number: "))

#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0

#Perform the successive approximations
while True:
    estimate = (estimate + x / estimate) / 2
    diference = abs(x - estimate ** 2)
    if diference <= tolerance:
       break
    elif x < 0:
        print("Please enter a positive number")
#Output the result
print("The program's estimate:", estimate)
print("Python's estimate:     ", math.sqrt(x))
导入数学
#从用户处接收输入号码
x=浮点(输入(“输入正数:”)
#初始化公差和估算值
公差=0.000001
估计值=1.0
#执行逐次逼近
尽管如此:
估算=(估算+x/估算)/2
差异=绝对值(x-估计**2)

如果差异可以通过将
input()
放入
while
循环来修复

import math

#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0

while True:

    # Receive the input number from the user
    x = float(input("Enter a positive number: "))

    estimate = (estimate + x / estimate) / 2
    diference = abs(x - estimate ** 2)
    if diference <= tolerance:
       break
    elif x < 0:
        print("Please enter a positive number")
--snip--
导入数学
#初始化公差和估算值
公差=0.000001
估计值=1.0
尽管如此:
#从用户处接收输入号码
x=浮点(输入(“输入正数:”)
估算=(估算+x/估算)/2
差异=绝对值(x-估计**2)
如果差异
elif x<0:
打印(“请输入正数”)
#从用户处接收输入号码
x=浮点(输入(“输入正数:”)

在代码中添加第四行。它会起作用的。尝试失败后,您没有再次收到输入

问题是您需要在while循环中重新请求用户输入,正如其他人已经提到的那样

这个答案的一个更彻底的版本是重构while循环内部的操作顺序。在代码中,在验证其是否大于零之前,对
x
运行数学运算。如果已知没有正整数的数学运算失败,那么代码中就会有一个bug,可能导致未处理的异常。这是另一个版本,带有if语句,因此我们在执行任何其他操作之前检查输入,这使得程序不太可能基于输入引发异常

导入数学
#初始化公差和估算值
公差=0.000001
估计值=1.0
#执行逐次逼近
尽管如此:
#从用户处接收输入号码
x=浮点(输入(“请输入正数:”)

如果您的问题已被编辑,以消除您对缺乏经验的歉意;不要认为这意味着人们不在乎,只是在一个公共问答论坛上,后面的人更容易阅读不包含这些内容的问题。此外,这里欢迎所有技能水平的人;你不需要证明你的问题是正确的谢谢你所做的一切,我的朋友。我感谢你花时间对我的问题作进一步的详细说明。真的帮助我了解我哪里出错了。
elif x < 0:
  print("Please enter a positive number") 
  # Receive the input number from the user
  x = float(input("Enter a positive number: "))