Functions_python
Functions_python
python
What is function?
A function is a named, reusable block of code that takes inputs (parameters), processes them,
and returns a result (output). Functions help break down complex problems into smaller,
manageable tasks. They allow you to write code once and use it multiple times, promoting
reusability and reducing redundancy. Functions can also have side effects, like modifying global
variables, or they can just return a value.
In one line:
A function is a block of code that takes inputs, performs a task, and returns an output.
Important terminology
1. Function Name:
The function name should be a valid identifier (alphanumeric characters and
underscores).
It cannot start with a number or contain spaces.
Function names should be descriptive, indicating what the function does.
By convention, function names in Python are written in lowercase, with words
separated by underscores (snake_case).
2. Defining a Function:
The function is defined using the def keyword, followed by the function name
and parentheses () (even if there are no parameters).
A colon : is used to indicate the start of the function body.
3. Parameters (Optional):
A function can take parameters (inputs) within the parentheses (). These are
optional; a function can have zero or more parameters.
Parameters are used to pass values into the function.
4. Function Body:
The function body contains the code that performs the action. It must be
indented (usually 4 spaces).
Python uses indentation to define the scope of the function body.
1. Built-in Functions:
Built-in functions are functions that are part of Python's standard library and
are always available for use without importing any modules.
2. User-defined Functions:
Functions created by the programmer to perform specific tasks, tailored to the
program's needs.
Defined using the def keyword.
Customizable and reusable.
Designed to handle tasks not covered by built-in functions.
Lambda Function Definition:
A lambda function in Python is a small, anonymous function defined using the
lambda keyword. Unlike regular functions defined with def, lambda functions
can have only a single expression and are used for short, simple operations.
Syntax