Python Documentation

Functions

Functions in Python

Functions in Python are blocks of reusable code that perform a specific task. They help in organizing code, improving readability, and reducing repetition.

Defining a Function

Functions are defined using the def keyword, followed by the function name and parentheses.

def greet(name):
return f"Hello, {name}!"

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

Function Parameters

Functions can take parameters, which are values you can pass to the function.

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

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

Default Parameters

You can set default values for parameters, which will be used if no argument is provided.

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

print(greet()) # Output: Hello, Guest!
print(greet("Alice")) # Output: Hello, Alice!

Return Statement

The return statement is used to exit a function and return a value.

def square(x):
return x * x

result = square(4)
print(result) # Output: 16

*args and **kwargs

These allow you to pass a variable number of arguments to a function.

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, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York