PYTHON FUNCTION:
EXAMPLE:
ADVANTAGE OF FUNCTION:
- Modularity: Functions allow you to break down complex tasks into smaller, more manageable pieces of code. This makes your codebase easier to read, understand, and maintain.
- Code Reusability: Once you've defined a function, you can call it multiple times with different arguments. This reduces code duplication and promotes reusability, which saves time and effort.
- Abstraction: Functions allow you to abstract away the implementation details of a certain task. This means you can use a function without needing to understand how it works internally, as long as you know what inputs it expects and what output it produces.
- Readability and Maintainability: Using well-named functions with descriptive parameters and docstrings improves the readability of your code. This makes it easier for you and other developers to understand and work with the codebase.
- Testing: Functions can be tested individually, making it easier to identify and fix issues. This modularity also makes unit testing more straightforward, as you can isolate specific parts of your code for testing.
- Collaboration: When working on a project with multiple developers, using functions makes it easier to divide the work into smaller units and collaborate efficiently.
- Encapsulation: Functions allow you to encapsulate logic within a specific scope. This helps prevent naming conflicts and unintended interactions between different parts of your code.
- Parameterization: Functions can accept parameters, which allows you to make your code more flexible. By changing the input parameters, you can customize the behavior of a function without modifying its implementation.
- Function Overloading: While Python doesn't support traditional function overloading like some other languages, you can achieve similar behavior by using default parameter values and variable-length argument lists.
- Namespace Isolation: Variables defined within a function have local scope, meaning they don't interfere with variables outside the function. This isolation helps prevent unintended variable modifications.
- Algorithmic Understanding: Breaking down complex algorithms into smaller functions can help you understand the algorithm step by step, leading to better debugging and optimization.
- Library and Module Design: Functions are essential for designing libraries and modules. They provide clear interfaces for users of your code and hide implementation details.
USER-DEFINED FUNCTION:
EXAMPLE:
CALLING A FUNCTION:
Function with No Arguments:
If the function doesn't require any arguments, you simply write the function name followed by parentheses.
EXAMPLE:
def say_hello():
print("Hello, world!")
# Calling the function
say_hello()
Function with Arguments:
If the function requires one or more arguments, you provide the necessary values inside the parentheses when calling the function.
EXAMPLE:
def greet(name):
print(f"Hello, {name}!")
# Calling the function with an argument
greet("GAURAV")
Function with Return Value:
If the function returns a value using the return statement, you can capture and use that returned value.
EXAMPLE:
def add(a, b):
result = a + b
return result
# Calling the function and using the returned value
sum_result = add(3, 5)
print(sum_result) # Output: 8
Variable Number of Arguments:
Functions can accept a variable number of arguments using *args for positional arguments or **kwargs for keyword arguments.
EXAMPLE:
def print_arguments(*args):
for arg in args:
print(arg)
# Calling the function with variable arguments
print_arguments(1, 2, 3) # Output: 1 2 3
def print_keyword_arguments(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with keyword arguments
print_keyword_arguments(a=1, b=2, c=3)
# Output:
# a: 1
# b: 2
# c: 3
RETURN STATEMENT:
EXAMPLE:
ANONYMOUS FUNCTION:
SYNTAX:
EXAMPLE:
PYTHON BUILT-IN FUNCTION:
Numeric Functions:
- abs(x): Returns the absolute value of x.
- round(x): Rounds x to the nearest integer.
String Functions:
- len(s): Returns the length of a string.
- str(x): Converts x to a string representation.
- upper(): Converts a string to uppercase.
Type Conversion Functions:
- int(x): Converts x to an integer.
- float(x): Converts x to a floating-point number.
- str(x): Converts x to a string.
Container Functions:
- list(iterable): Converts an iterable to a list.
- tuple(iterable): Converts an iterable to a tuple.
- set(iterable): Converts an iterable to a set.
Input/Output Functions:
- print(*objects, sep=' ', end='\n'): Prints objects to the standard output.
- input(prompt): Reads a line of text from the user.
Math Functions:
- max(iterable): Returns the maximum value from an iterable.
- min(iterable): Returns the minimum value from an iterable.
- sum(iterable): Returns the sum of values in an iterable.
Iteration and Iterables:
- range(start, stop[, step]): Generates a sequence of numbers.
- enumerate(iterable): Generates index-value pairs from an iterable.
Boolean Functions:
- bool(x): Converts x to a Boolean value.
- all(iterable): Returns True if all elements of the iterable are True.
- any(iterable): Returns True if any element of the iterable is True.
Sorting and Iteration:
- sorted(iterable): Returns a sorted list from the elements of an iterable.
- reversed(sequence): Returns a reverse iterator.
File Operations:
- open(file, mode): Opens a file for reading, writing, or appending.
0 Comments