python

Function


  • A Function is a block of code which runs when it is called.
  • Function helps to break the program into smaller chunks.
  • As program grows larger and larger, functions make it more organized and manageable.
  • functions avoids repetitions and makes code reusable.

 

Defining a Function

A function is defined using the ‘def’ keyword, followed by the function name, parentheses (which can include parameters), and a colon. The function body is indented.

Syntax:

def function_name(parameters):
   # block of code
   return value
 

Example:

def greet(name):
   return f"Hello, {name}!"
# Calling the function
print(greet("Alice"))  # Output: Hello, Alice!
 

 

Calling a Function

To call a function, use its name followed by parentheses, passing any required arguments.

Example:

result = greet("Bob")
print(result)  # Output: Hello, Bob!
 

 

1.Function Parameters

Functions can take zero or more parameters.

Positional Arguments

Positional arguments are passed to the function in the order they are defined.

Example:

def add(a, b):
   return a + b
print(add(2, 3))  # Output: 5
 

 

Keyword Arguments

Keyword arguments are passed to the function by explicitly naming the parameters.

Example:

def subtract(a, b):
   return a - b
print(subtract(b=5, a=10))  # Output: 5
 

 

Default Arguments

Default arguments are used when you want to provide default values for parameters. If the argument is not provided during the function call, the default value is used.

Example:

def greet(name="Guest"):
   return f"Hello, {name}!"
print(greet())         # Output: Hello, Guest!
print(greet("Alice"))  # Output: Hello, Alice!
 

 

Variable-Length Arguments

Functions can accept variable-length arguments using *args for positional arguments and **kwargs for keyword arguments.

Example:

def sum_all(*args):
   return sum(args)
print(sum_all(1, 2, 3, 4))  # Output: 10
def print_info(**kwargs):
   for key, value in kwargs.items():
       print(f"{key}: {value}")
print_info(name="Alice", age=30)  # Output: name: Alice, age: 30
 

 

2.Return Statement

The return statement is used to exit a function and optionally pass back an expression to the caller.

Example:

def square(x):
   return x * x
result = square(4)
print(result)  # Output: 16

A function without a return statement returns None by default.

 


python