Header Ads Widget

Ticker

6/random

Python Functions


Python Functions


In Python, a function is a reusable block of code that performs a specific task. Functions help in organizing code, making it more readable and modular. 


Here's a simple explanation with examples:


1. Function Definition:


```python

def greet(name):

    """This function greets the person passed in as a parameter."""

    print(f"Hello, {name}!")

# Example usage:

greet("Alice")

```


In this example, `greet` is a function that takes a parameter `name` and prints a greeting.


2. Return Statement:


```python

def add(a, b):

    """This function adds two numbers and returns the result."""

    sum_result = a + b

    return sum_result

# Example usage:

result = add(3, 5)

print(result)

```


The `add` function adds two numbers and returns the result, which is then printed.


3. Default Parameters:


```python

def power(base, exponent=2):

    """This function raises the base to the power of the exponent."""

    result = base ** exponent

    return result

# Example usage:

result1 = power(3)

result2 = power(2, 4)

print(result1, result2)

```


The `power` function has a default value for `exponent`, which is 2 if not provided.


4. Keyword Arguments:


```python

def person_info(name, age, city):

    """This function prints information about a person."""

    print(f"Name: {name}, Age: {age}, City: {city}")

# Example usage:

person_info(name="Bob", age=30, city="New York")

```


You can provide arguments by specifying the parameter names, making the code more readable.


5. Variable Scope:


```python

def modify_variable():

    """This function demonstrates variable scope."""

    x = 10 # Local variable

    print(f"Inside function: x = {x}")

x = 5 # Global variable

modify_variable()

print(f"Outside function: x = {x}")

```


The variable `x` inside the function is local, and it doesn't affect the global variable `x`.


These are basic examples, and Python functions can be more complex based on your needs. Functions enhance code reusability, readability, and maintainability.

Post a Comment

0 Comments