Functions in Python are blocks of organized, reusable code that perform a specific task. They allow you to break down your program into smaller, manageable pieces, making your code more modular, readable, and maintainable. Here's an overview of functions in Python:
1. Function Definition:
- Functions are defined using the
def
keyword followed by the function name and parentheses containing optional parameters. - The body of the function is indented and contains the code to be executed when the function is called.
Example:
def greet(name): print("Hello, " + name + "!")
2. Function Call:
- To execute the code inside a function, you call the function by using its name followed by parentheses containing arguments (if any).
- Arguments are the values passed to the function when it is called, which can be used inside the function's body.
Example:
greet("John") # Output: Hello, John!
3. Return Statement:
- Functions can optionally return a value using the
return
statement. - The
return
statement exits the function and optionally sends a value back to the caller.
Example:
def add(x, y): return x + y result = add(3, 5) print(result) # Output: 8
4. Parameters and Arguments:
- Parameters are placeholders for the values that a function expects to receive when it is called.
- Arguments are the actual values passed to the function when it is called.
Example:
def greet(name): print("Hello, " + name + "!") greet("Alice") # "Alice" is an argument passed to the function greet()
5. Default Parameters:
- You can specify default values for parameters in a function definition.
- If an argument is not provided when the function is called, the default value is used.
Example:
def greet(name="Guest"): print("Hello, " + name + "!") greet() # Output: Hello, Guest! greet("Bob") # Output: Hello, Bob!
6. Arbitrary Number of Arguments:
- You can define functions that accept an arbitrary number of arguments using
*args
or**kwargs
in the parameter list. *args
collects positional arguments into a tuple, while**kwargs
collects keyword arguments into a dictionary.
Example:
def sum_values(*args): total = 0 for num in args: total += num return total result = sum_values(1, 2, 3, 4, 5) print(result) # Output: 15
0 Comments