Geek Slack

Introduction to Python
About Lesson



Python Functions


Python Functions

A function in Python is a block of reusable code that performs a specific task. Functions allow you to break down your code into smaller, more manageable pieces.

1. Defining a Function

To define a function in Python, you use the def keyword followed by the function name and parentheses containing any parameters.

Example:

def greet():
    print("Hello, world!")

greet()

2. Function Parameters

You can pass parameters to a function by placing them within the parentheses when defining the function.

Example:

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

greet("Alice")

3. Return Statement

A function can return a value using the return statement.

Example:

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

result = add(3, 5)
print(result)

4. Default Parameters

You can specify default values for parameters in a function, which are used when the function is called without providing a value for those parameters.

Example:

def greet(name="world"):
    print("Hello, " + name)

greet()
greet("Alice")

5. Docstrings

Docstrings are used to provide documentation for functions. They are enclosed in triple quotes and appear as the first statement in a function.

Example:

def greet(name):
    """
    This function greets the person with the given name.
    """
    print("Hello, " + name)

greet("Alice")

Conclusion

Functions are a fundamental concept in Python programming, allowing you to encapsulate reusable code and make your programs more modular and easier to maintain. Understanding how to define, call, and work with functions is essential for writing efficient and organized code.

Join the conversation