Can I have more than one function with the same name?

can we use functions with same name in single program?
in this case which function definition will be invoked when we called evaluate(10) second time.

1 Like

One function can be given many names, but many functions cannot have the same name. If we happen to declare two functions of the same name, the latter one in the source listing is the one that will apply.

14 Likes

Thank you sir,clarified!

2 Likes

It’s not strictly true, if the source code is not all executed sequentially. The def block that was processed most recently to define a particular function name is the one that applies when that name is used to call a function. See the following example:

import random

for i in range(4):
  choice = random.randint(1, 2)
  if choice == 1:
    print("defining first version of the_function.")
    def the_function():
      print("\nI am the first version of the_function!")

  if choice == 2:
    print("defining second version of the_function.")
    def the_function():
      print("\nI am the second version of the_function!!")

the_function()

Output from a sample run:

defining second version of the_function.
defining second version of the_function.
defining second version of the_function.
defining first version of the_function.

I am the first version of the_function!
6 Likes

This seems more advanced than what the lessons have taught us up to this point.

1 Like

Hello @core1805653314, and welcome to the Codecademy Forums!

Yes, it is indeed more advanced than what the lessons have taught thus far. The example was provided in order to demonstrate an answer to this question:

While the provided example does address the question by demonstrating that we can redefine the name of an existing function, it is generally not a good idea to do so, unless there is a compelling reason for it. Such a technique can confuse programmers who read the code, and result in a buggy program. For that reason, Codecademy does not teach such a technique, at least as far as I am aware.

2 Likes

But why not just stick with examples that fall within what has been learnt so far? I feel thats better considering your audience

1 Like

As a former teacher, I’ll defend the moderator’s choice here; sometimes students’ questions (or other teachers’ answers) require the teacher (moderator in this case) to go beyond the scope of the lesson. The answer to the question is the answer to the question. What’s important for us to know at this point is, no, we shouldn’t use the same name for two different functions because different things can happen depending on your choices with more advanced code tools that we haven’t learned yet. Is that better?

1 Like

Sorry, it’s very interesting for me, means that a function call “can find” its function even in enother scope? Right?

1 Like

The scoping rules that apply to variables also apply to functions. We can define a function that is local to the scope of a function that contains it. However the outer function can return a reference to the local function that it contains. That would make the local inner function accessible to the outside, under a name chosen by the caller of the outer function. To arrange for that, just assign the returned function reference to a variable.

A function can even return references to multiple functions by including them in a returned list or dictionary.

We can experiment with examples upon request.

Yes, PLEASE! It’s very interesting! Thank you in advance.

Here’s an example of a function factory that defines an inner polynomial evaluator function and returns it for use outside the function factory:

def polynomial_function_factory(coeffs):
  # coeffs: a list of polynomial coefficients
  
  # define customized polynomial function with coeffs built in
  def polynomial_function(x):
    # initialize the result accumulator
    result = 0
    # iterate through the coefficients
    for coeff in coeffs:
      # multiply result accumulator by x and add coefficient
      result = result * x + coeff
    # result is complete; return it
    return result
  
  # return the function definition
  return polynomial_function

# create the function by calling the factory; save as poly
poly = polynomial_function_factory([2, 4, 1])
# call the function
print(poly(1))
print(poly(2))
print(poly(3))

Output:

7
17
31
3 Likes

Here’s a function factory that is recursive:

def power_function_factory(max_power):
  # return a list of power functions
  # with exponents from 0 to max_power, inclusive
  if max_power == 0:
    # base case
    return [lambda n: n ** 0]
  else:
    # recursive case
    return power_function_factory(max_power - 1) + [lambda n: n ** max_power] 

funcs = power_function_factory(7)

square = funcs[2]
cube = funcs[3]
fourth = funcs[4]

print(square(3))
print(cube(5))
print(fourth(2))

Output:

9
125
16
2 Likes

Thank you very much for the exapmles!! It’s impressive, I’ll chew it for some time :slight_smile:

1 Like

Hello!
What could be the possible benefit of using this kind of design pattern over using less complex albeit longer, simpler function definitions?
How do you balance this with the principle of KISS (Keep it Simple, Stupid)?

Thank You