Python functions


Functions in Python

A function in Python is a reusable block of code that performs a specific task. Functions help organize code, promote code reusability, and make it easier to manage and understand complex programs. You can define your own functions or use built-in functions provided by Python.

Defining a Function

You can define a function using the def keyword, followed by the function name and parentheses. Any parameters the function takes are specified within the parentheses. The function body is indented below the definition.

Syntax

def function_name(parameters): # Code block return value # Optional
  • function_name: The name you choose for the function.
  • parameters: Input values (arguments) the function can accept; these are optional.
  • return: A statement used to return a value from the function (optional).

Example 1: A Simple Function

def greet(): print("Hello, world!") greet() # Calling the function

Output:

Hello, world!

In this example, the greet function prints "Hello, world!" when called.


Example 2: Function with Parameters

You can define a function that accepts parameters to customize its behavior.

def greet(name): print(f"Hello, {name}!") greet("Alice") # Calling the function with an argument greet("Bob")

Output:

Hello, Alice! Hello, Bob!

Here, the greet function takes one parameter (name) and uses it to print a personalized greeting.


Example 3: Function with Return Value

A function can return a value using the return statement.

def add(a, b): return a + b # Return the sum of a and b result = add(3, 5) # Calling the function and storing the result print(result)

Output:

8

In this example, the add function takes two parameters and returns their sum.


Example 4: Function with Default Parameter Values

You can define default values for parameters in a function. If the caller does not provide a value, the default is used.

def greet(name="Guest"): print(f"Hello, {name}!") greet() # Uses default value greet("Alice") # Uses provided value

Output:

Hello, Guest! Hello, Alice!

Here, if no name is provided, the function defaults to "Guest".


Example 5: Variable-Length Arguments

You can define functions that accept a variable number of arguments using *args for non-keyword arguments and **kwargs for keyword arguments.

Using *args

def sum_all(*args): return sum(args) # Sum of all arguments result = sum_all(1, 2, 3, 4, 5) print(result)

Output:

15

In this example, the sum_all function can take any number of positional arguments.

Using **kwargs

def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=25, city="New York")

Output:

name: Alice age: 25 city: New York

Here, print_info can take any number of keyword arguments and prints them.


Example 6: Lambda Functions

Python also supports anonymous functions (lambda functions), which are small, one-line functions defined using the lambda keyword.

Syntax

lambda arguments: expression

Example of a Lambda Function

add = lambda x, y: x + y print(add(3, 5)) # Calling the lambda function

Output:

8

In this example, add is a lambda function that takes two arguments and returns their sum.


Scope of Variables in Functions

  • Local Variables: Variables defined inside a function are local to that function and cannot be accessed outside.
  • Global Variables: Variables defined outside of functions can be accessed inside functions, but you must declare them as global if you want to modify them.

Example of Local and Global Variables

x = 10 # Global variable def modify(): global x # Declare x as global to modify it x += 5 print(f"Inside function: {x}") modify() print(f"Outside function: {x}")

Output:

Inside function: 15 Outside function: 15

In this example, the global variable x is modified inside the modify function.


Summary

  • Functions are reusable blocks of code defined using the def keyword.
  • They can accept parameters, return values, and have default parameter values.
  • You can define functions with variable-length arguments using *args and **kwargs.
  • Lambda functions provide a way to create small anonymous functions.
  • Understanding the scope of variables is important when working with functions.

Functions are essential for organizing and structuring code in Python, making it modular and easier to read and maintain.