Python

Writing Your First Python Functions - Defining and Calling


Introduction

Functions are a fundamental concept in Python and are used to encapsulate reusable pieces of code. In this guide, we will explore how to define and call your first Python functions.

Defining a Python Function

To define a function in Python, use the def keyword followed by the function name and a pair of parentheses. Here's a simple example:

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

In this example, we defined a function called greet that takes one argument name and prints a greeting message.

Calling a Python Function

To call a Python function, use its name followed by parentheses, passing any required arguments. Here's how you can call the greet function:

greet(`Alice`)
greet(`Bob`)
        

When you call the function with different names, it prints personalized greetings.

Function Parameters and Return Values

Functions can have parameters (inputs) and return values (outputs). Here's an example of a function with parameters and a return value:

def add(x, y):
    result = x + y
    return result
        

In this example, the add function takes two arguments (x and y) and returns their sum. You can call it like this:

result = add(5, 3)
print(`Sum:`, result)
        

The add function returns the result, which is then printed.

Conclusion

Python functions are powerful and allow you to structure your code in a more organized and reusable way. You've now learned how to define and call functions, and you can start creating more complex and modular Python programs.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.