【问题标题】:Python - Problems with a while loopPython - while 循环的问题
【发布时间】:2020-02-24 04:41:36
【问题描述】:

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

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))

【问题讨论】:

  • 您的问题已被编辑,以消除您对缺乏经验的歉意;不要认为这意味着人们不在乎,只是在公共问答论坛中,那些追随者更容易阅读不包含这些内容的问题。此外,这里欢迎所有技能水平;你不需要证明你的问题。 :)

标签: python input output


【解决方案1】:

您可以通过将 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--

【讨论】:

    【解决方案2】:

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

    这个答案的更彻底的版本也是重构 while 循环内的操作顺序。在代码中,您在验证 x 是否大于零之前运行数学运算。如果已知数学在没有正整数的情况下会失败,那么您的代码中就会有一个错误,可能导致未处理的异常。这是另一个切换 if 语句的版本,因此我们在做任何其他事情之前检查输入 - 这使得程序不太可能根据输入抛出异常。

    import math
    
    #Initialize the tolerance and estimate
    tolerance = 0.000001
    estimate = 1.0
    
    #Perform the successive approximations
    while True:
        # Receive the input number from the user
        x = float(input("Please enter a positive number:"))
        if x <= tolerance:
            print("Invalid input.")
            continue
        else:
            estimate = (estimate + x / estimate) / 2
            diference = abs(x - estimate ** 2)
            break
    
    #Output the result
    print("The program's estimate:", estimate)
    print("Python's estimate:     ", math.sqrt(x))
    

    【讨论】:

    • 感谢您所做的一切,我的朋友。感谢您抽出宝贵时间详细了解我的问题。真的可以帮助我了解我哪里出错了。
    【解决方案3】:
    elif x < 0:
      print("Please enter a positive number") 
      # Receive the input number from the user
      x = float(input("Enter a positive number: "))
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      相关资源
      最近更新 更多