Python def function: How do you specify the end of the function?

后端 未结 8 1661
迷失自我
迷失自我 2020-12-04 19:21

I\'m just learning python and confused when a \"def\" of a function ends?

I see code samples like:

def myfunc(a=4,b=6):
    sum = a + b
    return su         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 20:00

    To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:

    def foo():
        if bar:
            print "bar"
    
    print "baz" # ends the if and foo at the same time
    

    The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.

    Lines with no statement, no matter the indentation, does not matter

    def foo():
        print "The line below has no indentation"
    
        print "Still part of foo"
    

    But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:

    def foo():
        print "Still correct"
       print "Error because there is no block at this indentation"
    

    Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.

    BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.

提交回复
热议问题