Does the order of functions in a Python script matter?

前端 未结 2 757
无人共我
无人共我 2021-02-03 18:04

Let\'s say I have two functions in my script: sum_numbers and print_sum. Their implementation is like this:

def sum_numbers(a, b):
             


        
2条回答
  •  野性不改
    2021-02-03 18:14

    It doesn't matter in which order the functions are created. It only matters when the call to the function is done:

    def print_sum(a, b):
        print(sum_numbers(a, b))
    
    def sum_numbers(a, b):
        return a + b
    
    print_sum(1, 3)
    # 4
    

    that works because at the time print_sum is called both functions do exist. However if you call the function before defining sum_numbers it would fail because sum_numbers isn't defined yet:

    def print_sum(a, b):
        print(sum_numbers(a, b))
    
    print_sum(1, 3)
    
    def sum_numbers(a, b):
        return a + b
    

    throws:

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
     in ()
          2     print(sum_numbers(a, b))
          3 
    ----> 4 print_sum(1, 3)
          5 
          6 def sum_numbers(a, b):
    
     in print_sum(a, b)
          1 def print_sum(a, b):
    ----> 2     print(sum_numbers(a, b))
          3 
          4 print_sum(1, 3)
          5 
    
    NameError: name 'sum_numbers' is not defined
    

提交回复
热议问题