如何阻止我的功能?

时间:2015-05-10 05:17:41

标签: python-3.x break

当条件满足时,如何让我的功能停止? 例如,在我的以下代码中,当用户输入:" q" for(quit),我希望我的功能简单地停止。 我已尝试使用" break"声明,但它不起作用。

def main():
    shape = input("Enter shape to draw (q to quit): ").lower()
    while shape != 'triangle' and shape != 'square' and shape != 'q':
            print("Unknown shape. Please try again")
            shape = input("Enter shape to draw (q to quit): ").lower()
    if shape == "q":
        print("Goodbye")  
        break #Python not happy with the indentation.

def get_valid_size():
    size = int(input("Enter size: "))
    while size < 1:
        print("Value must be at least 1")
        size = int(input("Enter size: "))
main()
get_valid_size()

当我运行它时,它执行:

Enter shape to draw (q to quit): q Goodbye Enter size:

我不希望它要求尺寸。

2 个答案:

答案 0 :(得分:2)

return将退出一个函数,将控制权返回给最初调用该函数的任何函数。如果您想了解更多信息,谷歌的短语是“退货声明”。

break将退出循环as described here

尝试类似:

def main():
    shape = input("Enter shape to draw (q to quit): ").lower()
    while shape != 'triangle' and shape != 'square' and shape != 'q':
            print("Unknown shape. Please try again")
            shape = input("Enter shape to draw (q to quit): ").lower()
    if shape == "q":
        print("Goodbye")  
        return
    get_valid_size()

def get_valid_size():
    size = int(input("Enter size: "))
    while size < 1:
        print("Value must be at least 1")
        size = int(input("Enter size: "))
main()

答案 1 :(得分:1)

break仅用于退出for循环,while循环和try循环。

return将退出具有指定值的函数。只需使用return即可返回None值,而使用return Truereturn False将分别返回true和false。您也可以返回一个变量,例如,返回您使用x的变量return x