return True stop the loop in Python?

前端 未结 3 479
我在风中等你
我在风中等你 2021-01-28 03:10

I am still a beginner but does not know why the \"return True\" in a \"for loop\" stop the loop after the first pass. If I use something else than \"return\", everything is fine

3条回答
  •  情书的邮戳
    2021-01-28 03:53

    return statement is to return a value from a function. So, if you use return the control will be transferred to the calling function.

    If you want to break out of the loop, you need to use break statement.

    For example,

    def tempFunc1():
        i = 1
        return i
        print "leaving tempFunc1"
    
    print tempFunc1()
    

    It prints just 1. It doesnt print leaving tempFunc1 because, the function has returned to the caller before executing the print "leaving tempFunc1" statement.

提交回复
热议问题