In Python, a function is a block of code that can perform a specific task and return a result. Functions help break down large and complex problems into smaller, manageable tasks. This makes the code easier to understand and maintain.
A function is created using the def
keyword, followed by the function name, and the function’s parameters inside parentheses. The function body is indented and contains the statements to be executed. The function is executed by calling it.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result) # Output: 7
In this example, the add_numbers
function takes two parameters a
and b
, adds them, and returns the result. The function is called and the result is stored in the result
variable.
Function Arguments
Functions can take various types of arguments, such as required arguments, keyword arguments, and default arguments.
Required Arguments
Required arguments are the basic type of function arguments. They are positional and must be passed in the correct order.
def greet(name):
print("Hello, " + name)
greet("John") # Output: Hello, John
Keyword Arguments
Keyword arguments are arguments that are passed to a function by assigning a value to the argument name. The order of the arguments doesn’t matter in this case.
def greet(name, message):
print("Hello, " + name + ". " + message)
greet(message="How are you?", name="John") # Output: Hello, John. How are you?
Default Arguments
Default arguments are arguments that take a default value if no value is provided for the argument.
def greet(name, message="How are you?"):
print("Hello, " + name + ". " + message)
greet("John") # Output: Hello, John. How are you?
Return Statement
The return
statement is used to return a value from a function. The return statement terminates the function and the value is returned to the caller. If a return statement is not present in a function, the function returns None
.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result) # Output: 7
Local and Global Variables
Variables declared inside a function are called local variables and are only accessible inside the function. Variables declared outside a function are called global variables and are accessible from anywhere in the code.
x = 10 # Global variable
def print_x():
print(x)
print_x() # Output: 10
In this example, the variable x
is a global variable and can be accessed from inside the print_x
function.
def set_x(value):
x = value # Local variable
set_x(20)
print(x) # Output: 10
In this example, the variable x
is a local variable which can get accessed within the function only.