How To Define a Function in Python

Published on Aug. 22, 2023, 12:15 p.m.

To define a function in Python, you use the def keyword, followed by the function name, a pair of parentheses, and a colon. Any parameters that the function takes should be listed inside the parentheses. Here’s an example:

def greet(name):
    print("Hello, " + name + "!")

In this example, we define a function called greet that takes one parameter name. When the function is called, it will print a greeting message to the console with the name that was passed in as an argument.

You can also include a return statement in your function to return a value to the caller. Here’s an example:

def add(a, b):
    return a + b

In this example, we define a function called add that takes two parameters a and b. The function returns the sum of these two values.

Tags:

related content