定义函数重复循环

时间:2014-10-27 05:32:45

标签: python

简单修复,但如何才能停止循环?输出是它只是反复询问值。还有一种方法可以检查所有值,以确保在20到40之间?

def main():    
    print("Welcome to the autostacker")
    print(getDim())

def getDim():
    height = int(input("Enter the height: "))
    width = int(input("Enter the width: "))
    length = int(input("Enter the width: "))
    return getDim()


main()

2 个答案:

答案 0 :(得分:0)

我认为getDim()中的返回声明应该归咎于循环。您可以检查值是否在范围内,如下所示。

def main():    
    print("Welcome to the autostacker")
    print(getDim())

def getDim():
    height = int(input("Enter the height: "))
    width = int(input("Enter the width: "))
    length = int(input("Enter the width: "))
    if 20 <= height <=40 and 20 <= width <= 40 and 20 <= length <= 40:
         print "all the values lie in the range"
         # DO WHAT YOU WANT
    else:
        print " values are not in range"
        # DO SOMETHING ELSE
    return height, width,length

main()

答案 1 :(得分:0)

这样的东西
def main():    
    print("Welcome to the autostacker")
    h, w, l = getDim()

    if 20 <= h <= 40:
        if 20 <= w <= 40:
            if 20 <= l <= 40:
                print "height is %d width is %d length is %d" % (h, w, l)
            else:
                print 'length out of range'
        else:
            print 'width out of range'
    else:
        print 'height out of range'




def getDim():
    height = int(input("Enter the height: "))
    width = int(input("Enter the width: "))
    length = int(input("Enter the length: "))
    return height, width, length

main()

确保你不要在getDim中调用getDim,除非你有条件最终让它停止调用自己。