0

我目前正在编写一个解决勾股定理的程序。但是,我在程序中有一个错误。每当我为长度 a 或 b 输入负数时,它会打印出“A 不能小于零”,但会继续求解 C 并打印出 C 的长度,即使用户尚未输入 b。我怎样才能做到这一点,当用户输入一个负数时,它会打印出语句“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 + "."
4

4 回答 4

3

You missed one indentatino level. Try it like this :

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 + "."
于 2013-11-07T17:26:05.970 回答
2

Try to avoid using nested if when designing the program flow. It leads to this kind of bug (missing one level of indentation). Big chunks of code inside if blocks and many nested if blocks make the program harder to follow and reason about.

Instead, you can ask again until the input is valid:

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's advice is good, wrap it into a function for reuse:

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

Then use:

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,
)
于 2013-11-07T17:26:10.390 回答
2

首先,如果你想不断检查你的输入,你将不得不使用一个循环。如中,该算法的伪代码应该是:

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()
于 2013-11-07T17:46:32.513 回答
0

免责声明:我使用的是不同版本的 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,因此您可以执行 while 循环(否则您会收到错误,解释器不知道 a,b 到那时)。然后它分别重复要求 a,b 的语句,直到你得到有效的输入(一般意义上的有效,我们不做错误检查,如果你使用字符串会发生什么??>.<)现在打印有点时髦,我肯定会查看 Python 文档,看看 %d %s 等是什么。然后我们将方法的返回值(参见上面的 def py_theorem)连同一个单元一起传递给字符串。请注意,该函数分别采用两个参数 a、b。

于 2013-11-07T17:48:58.367 回答