我目前正在编写一个将解决毕达哥拉斯定理的程序。但是,我的程序中有一个错误。每当我将长度A或B的负数放置时,它都会打印出“ A不能小于零”,但是继续求助于C无论如何,即使用户尚未输入B,也可以打印出C的长度。我该如何制作它,因此当用户输入一个负数时,它会打印出“ A不能小于零”,然后再次循环以输入侧面的长度,而不是现在在该侧面打印出来的情况声明它将其重定向到最后?

这是我的代码:

 import math
    print"This program will solve the pythagorean theorem for you"
    unit=raw_input('Enter the unit you will be using')
    a=float(raw_input('Enter the length of side a'))
    if a<=0:
      print"A cannot be less than zero"
    else:
        b=float(raw_input('Enter the length of side b'))
    if b<=0:
      print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."
有帮助吗?

解决方案 2

首先,如果您想不断检查输入,则必须使用循环。如在其中,该算法的suedocode应该为:

Loop Begin
Check the value of a and b
If a or b is less than 0 then ask for input again
Otherwise, continue

请注意,该算法 跑步 至少 一次。

这基本上就是伪模 应该 看起来像。因此,在这种情况下,您可以使用 do-while 循环结构。在Python,没有类似的东西,所以我们 仿真 它:

import math


def take_in():
    a = raw_input("Enter the value of side a -> ")
    b = raw_input("Enter the value of side b -> ")

    # Trying to convert to a float
    try:
        a, b = float(a), float(b)
        # If successfully converted, then we return
        if a > 0 and b > 0:
            return a, b
    except ValueError:
        pass
    # If we cannot return, then we return false, with a nice comment

    print "Invalid input"
    return False


def main():
    # Calling the function at least once
    valid = take_in()

    # While we are not getting valid input, we keep calling the function
    while not valid:
        # Assigning the value to valid
        valid = take_in()

    # Breaking the return tuple into a and b
    a, b = valid
    print math.sqrt(a ** 2 + b ** 2)


if __name__ == '__main__':
    main()

其他提示

您错过了一个契约水平。这样尝试:

if a<0:
  print"A cannot be less than zero"
else:
    b=raw_input('Enter the length of side b')
    b=float(b)
    if b<0:
        print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."

尝试避免使用嵌套 if 设计程序流程时。它导致这种错误(缺少一个凹痕)。里面的大块代码 if 块和许多嵌套 if 块使该程序更难遵循和推理。

相反,您可以再次询问,直到输入有效为止:

a = -1
while a < 0:
    try:
        a=float(raw_input('Enter the length of side a'))
    except ValueError:
        pass
    if a<0:
        print "A cannot be less than zero"

弗雷德(Fred)的建议很好,将其包含在重复使用的功能中:

def validate(initial, prompt, test, message, typecast=str):
    value = initial
    while not test(value):
        try:
            value = typecast(raw_input(prompt))
        except ValueError:
            print "Invalid value"
            continue

        if not test(value):
            print message
            continue

        return value

然后使用:

a = validate(
    initial = -1, 
    prompt = 'Enter the length of side A', 
    test = lambda x: x >= 0,
    message = "A cannot be less than zero",
    typecast = float
)
b = validate(
    initial = -1, 
    prompt = 'Enter the length of side B', 
    test = lambda x: x >= 0,
    message = "B cannot be less than zero",
    typecast = float,
)

免责声明:我正在使用不同版本的Python,所以里程可能会有所不同

import math

a = 0
b = 0

def py_theorem(a, b):
    return(a**2 + b**2)


unit = raw_input('Enter the unit you will be using: ')

while a <= 0:
a = float(raw_input('Enter the length of side A: '))
if a <= 0:
    print('A cannot be less than 0.')

while b <= 0:
b = float(raw_input('Enter the length of side B: '))
if b <= 0:
    print('B cannot be less than 0.')

print('The length of the 3rd side C is %d %s') % (py_theorem(a,b), unit)

现在,如果您查看我的代码A,则B最初是0,因此您可以执行WALE循环(否则会遇到错误,解释器不知道A,B到那时)。然后,它分别重复陈述a,b,直到获得有效输入(从一般意义上有效,我们没有错误检查,如果您使用字符串?我一定会研究Python文档,看看%D%S等是什么。然后,我们将方法(请参阅def py_theorem up top)与单元一起传递到字符串。请注意,该函数分别为两个参数A,B。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top