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.

9 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!
3 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.

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