PYTHON

Defining and calling functions


Defining a Function

To define a function in Python, use the def keyword followed by the function name and parentheses (). Inside the parentheses, you can specify parameters that the function can take. Then, use a colon : and indent the code block that makes up the function's body.

def greet(name):
    """Function to greet a person with their name."""
    message = f"Hello, {name}! Welcome to codersmile.com."
    return message

 

Calling a Function

To call a function, simply use the function name followed by parentheses (), and pass any required arguments inside the parentheses.

def greet(name):
    """Function to greet a person with their name."""
    message = f"Hello, {name}! Welcome to codersmile.com."
    return message
    
# Calling the greet function
welcome_message = greet("Alice")
print(welcome_message)
  • def greet(name): defines a function named greet that takes one parameter name.
  • message = f"Hello, {name}! Welcome to codersmile.com." creates a message string using the name provided.
  • return message returns the message string.

 

Another Example with Multiple Parameters

Here's a function that adds two numbers:

def add_numbers(a, b):
    """Function to add two numbers."""
    return a + b
    
# Calling the add_numbers function
result = add_numbers(5, 3)
print(result)  # Output will be 8

 


PYTHON