DEV Community

Mahalakshmi C
Mahalakshmi C

Posted on

What Happens When We Define the Same Function Multiple Times? In Python

What Happens When We Define the Same Function Multiple Times?

In Python, if we define the same function name more than once, the latest function definition replaces the previous definition.

When we call that function, Python executes the latest definition.

Example:

def greet():
    print("Hello")

def greet():
    print("Welcome to Python")

greet()
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome to Python
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. First, we define the greet() function, which prints "Hello".
  2. Next, we define another function with the same name greet().
  3. The second definition replaces the first one.
  4. When we call greet(), Python executes the second function.

Conclusion

  • In Python, a function name can be defined multiple times, but only the latest definition is available when the function is called. The previous definition is replaced by the new one.
  • Therefore, we should use unique function names when we want to perform different tasks.
  • Unlike some other programming languages, Python does not support traditional function overloading based only on different parameters.

Top comments (0)