Which keyword is used to define a function in Python?

Python defines a function with the def keyword. To maintain clarity and prevent ambiguity in the language, the keyword def is only used for function definitions. Syntax to define a function is:

def square(num):
    """
    This function takes a num as input
    and returns its square.
    """
    return num * num

# Using the function
result = square(5)
print(f"The square of 5 is {result}")
# The f before the string indicates an f-string, which allows embedding
# variables directly in the string.

Key Features of Functions Defined with def

  1. Reusability:
    Functions allow code to be reused multiple times, reducing redundancy.
  2. Encapsulation:
    Functions encapsulate logic, making programs easier to read and maintain.
  3. Parameters and Return Values:
    Functions can accept arguments (parameters) and return results.