Skip to main content
Practice

Creating Reusable Code Blocks with Functions

In programming, a Function is a block of code designed to perform a specific task, and can be called upon whenever needed.

Functions play a critical role in enhancing the reusability of code.

By using functions, you can efficiently handle specific tasks by calling a pre-defined block of code, rather than writing repetitive code for the same task.

How to Define a Function
def function_name(parameters):
code_block

In Python, functions start with the def keyword, and the line with def is followed by a colon (:).

The function_name is used to identify the function, and the rules for function names are the same as variable names (use of letters, digits, underscores).

The line after the colon (:) uses indentation to mark the code block, where the tasks performed by the function are implemented.

You can define parameters for use within the function, if needed.

To return the result of the work performed by the function, use the return keyword.

Example of Function Definition
# Define the greet function using the name parameter
def greet(name):
# Use the name parameter to create and return a string
return f"Hello, {name}!"

# Hello, CodeBuddy!
print(greet("CodeBuddy"))

In the example above, the greet function uses the name parameter to generate the string f"Hello, {name}!" and returns the generated string using the return keyword.

When calling the defined function, use greet("CodeBuddy") by appending parentheses (()) to the function name.

Within the parentheses, pass the required arguments (in this example, "CodeBuddy") to the function.

Using only the function name without parentheses will refer to the function object itself, and not execute the function.

To call the function, always append parentheses to the function name, and include the required arguments within them.

Example of Calling a Calculation Function
def calculate(num1, num2):
return num1 * num2 + 10

print(calculate) # Outputs the function object
print(calculate(5, 3)) # 25
print(calculate(2, 4)) # 18

In the code above, the calculate function uses two parameters, num1 and num2, to compute num1 * num2 + 10, and returns the result using the return keyword.

Printing calculate outputs the function object, including the location where the function is stored, but does not perform any intended numeric operations.

In contrast, calculate(5, 3) and calculate(2, 4) return 25 and 18, respectively.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.