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()
Output:
Welcome to Python
Explanation:
- First, we define the
greet()function, which prints "Hello". - Next, we define another function with the same name
greet(). - The second definition replaces the first one.
- 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)