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
greetis 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
greetis called with the argument"John". - The function returns the string
"Hello, John!", which is stored in the variablemessage. - The
printfunction 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_defaulthas a default parameternameset 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
addtakes two argumentsaandb. - 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
multiplyfunction takes two argumentsaandb. - It calculates their product and returns the result.
- The
totalvariable, defined outside the function, stores the result of themultiplyfunction 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
lambdafunctionsquaretakes an argumentx. - It returns the square of
x. - The result of the
squarefunction is printed, which is25for the input5.
These are the fundamental aspects of Python functions that will help you write modular and efficient code.
0 Comments