我目前正在编写一个程序来解决毕达哥拉斯定理。然而,我在程序中有一个bug。每当我输入一个长度为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 + "."发布于 2013-11-07 17:46:32
首先,如果你想要不断地检查你的输入,你必须使用一个循环。与其中一样,算法的psuedocode应该是:
Loop Begin
Check the value of a and b
If a or b is less than 0 then ask for input again
Otherwise, continue请注意,算法必须至少运行一次。
这基本上就是psuedocode应该看起来的样子。因此,在这种情况下,可以使用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-07 17:26:05
你错过了一个契约级。试着这样做:
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-07 17:26:10
在设计程序流时尽量避免使用嵌套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,
)https://stackoverflow.com/questions/19842500
复制相似问题