Functions are defined using the def
keyword:
def greet(name):
print("Hello", name)
greet("Jina")
# Output: Hello Jina
def add(a, b):
return a + b
result = add(5, 3)
# Output: 8
def show(name="guest")
Python provides functions like len()
, type()
, and print()
out of the box.
A function calling itself:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
Anonymous functions for quick computations:
square = lambda x: x ** 2
print(square(4)) # Output: 16
def greet(name):
"""Displays a welcome message"""
print("Hello", name)
Functions are central to writing clean and scalable Python code. Learning to define them, manage arguments, and apply advanced concepts like recursion or lambda expressions is key to mastering the language.