A:你从来没有把最大的从没有分配出去。
B:如果float(inp)失败了,你还是要继续。你不应该这样做。虽然你可以将那些if/elif语句移到try块中,但我建议你不要这样做,因为这样会冒着意外捕获不应该捕获的语句的风险。相反,使用try/except的被忽略的块else。
在同一行中,除了你想要的错误,而不是所有的错误,这只是一个好的实践。
C:不需要继续largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except ValueError: #and not all errors!
print "Invalid input"
else:
# This block will execute if no exception is caught.
# Yes, this is valid python.
if smallest is None: #first number!
smallest = num
largest = num
elif num < smallest:
smallest = num
elif num > largest:
largest = num
print "Maximum is", largest
print "Minimum is", smallest