Does the function order operate in a Python script?

Say I have two functions in a script: sum_numbersand print_sum. Their implementation is as follows:

def sum_numbers(a, b):
    return a + b

def print_sum(a, b):
    print(sum_numbers(a, b))

So my question is: does it have the order in which the function is written? If I wrote a function first print_sum, then sum_numberswould the code work? If the answer is yes, does it always work?

+6
source share
2 answers

The only thing that worries Python is that the name is determined when it is actually being looked up. All this.

In your case, this is just fine, the order doesn't really matter, since you just define two functions. That is, you simply enter two new names, without searching.

, ( , ) :

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(2, 4)

def sum_numbers(a, b):
    return a + b

(NameError), (sum_numbers), .

, , ; Python, (, JavaScript).

+10

, . :

def print_sum(a, b):
    print(sum_numbers(a, b))

def sum_numbers(a, b):
    return a + b

print_sum(1, 3)
# 4

, print_sum , . , sum_numbers, , sum_numbers :

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b

:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> 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
+7

All Articles