How do you create and use functions in Python?

Creating and using functions in Python is a fundamental concept that allows you to encapsulate blocks of code and reuse them whenever needed. Here’s how you can create and use functions in Python:

1. Function Definition: To define a function in Python, you use the def keyword followed by the function name and a pair of parentheses. Inside the parentheses, you can specify the function’s parameters (input) if any. The function block is indented and contains the code that the function will execute.





def my_function(param1, param2):
    # Function code goes here
    result = param1 + param2
    return result

2. Function Call: To use a function, you call it by its name followed by parentheses. You can pass arguments (values) to the function if it expects parameters. The function will execute the code inside its block and return a result if specified.





result = my_function(10, 20)
print(result)  # Output: 30

3. Default Parameters: You can define default values for function parameters. If an argument is not provided for a parameter, it will take the default value.





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

greet("Alice")  # Output: Hello, Alice
greet("Bob", "Hi")  # Output: Hi, Bob

4. Return Statement: Functions can return values using the return statement. When the function is called, the value specified in the return statement will be returned to the caller.





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

result = add(5, 3)
print(result)  # Output: 8

5. Multiple Return Values: A function can return multiple values as a tuple, and you can unpack the values into variables.





def calculate(a, b):
    sum = a + b
    product = a * b
    return sum, product

s, p = calculate(3, 5)
print(s)  # Output: 8
print(p)  # Output: 15

6. Variable Scope: Variables defined inside a function have local scope and are not accessible outside the function. However, you can access global variables from within a function using the global keyword.





global_var = 10

def my_function():
    local_var = 20
    print(global_var)  # Output: 10
    print(local_var)  # Output: 20

my_function()
print(global_var)  # Output: 10

Functions in Python allow you to write modular and reusable code, making your programs more organized and easier to maintain.

Leave a Reply