Introduction to Functions:
Functions are blocks of organized, reusable code designed to perform a specific task. They help break down complex programs into smaller, manageable chunks, improving code readability and reusability.
Defining a Function:
In Python, functions are defined using the def
keyword, followed by the function name and parentheses containing optional parameters.
Example:
pythondef greet(name):
return f"Hello, {name}!"
Explanation:
- The function
greet
is defined with one parametername
. - It returns a string that greets the input
name
.
Calling a Function:
To execute a function and obtain its result, you call it with the required arguments.
Example:
pythonmessage = greet("John")
print(message)
:
- The function
greet
is called with the argument"John"
. - The function returns the string
"Hello, John!"
, which is stored in the variablemessage
. - The
print
function displays the value ofmessage
.
Default Parameters:
Functions can have default parameter values, which are used when an argument is not provided during the function call.
Example:
pythondef greet_default(name="Guest"):
return f"Hello, {name}!"
Explanation:
- The function
greet_default
has a default parametername
set to"Guest"
. - If no argument is provided, it will greet the guest; otherwise, it will greet the provided name.
Returning Values:
Functions can return values using the return
statement. They can return one or multiple values.
Example:
pythondef add(a, b):
return a + b
Explanation:
- The function
add
takes two argumentsa
andb
. - It returns their sum.
Scope of Variables:
Variables defined inside a function have local scope and are accessible only within the function. Variables defined outside the function have global scope.
Example:
pythondef multiply(a, b):
result = a * b
return result
total = multiply(3, 5)
print(total)
Explanation:
- The
multiply
function takes two argumentsa
andb
. - It calculates their product and returns the result.
- The
total
variable, defined outside the function, stores the result of themultiply
function call, and then it's printed.
Lambda Functions:
Lambda functions, also known as anonymous functions, are concise functions defined using the lambda
keyword.
Example:
pythonsquare = lambda x: x**2
print(square(5))
Explanation:
- The
lambda
functionsquare
takes an argumentx
. - It returns the square of
x
. - The result of the
square
function is printed, which is25
for the input5
.
These are the fundamental aspects of Python functions that will help you write modular and efficient code.
0 Comments