Defining Functions in Python
Introduction to Functions in Python
Welcome to the first lesson of our course, "Optimization with SciPy." In this lesson, we're going to lay the foundation by learning how to define functions in Python. Functions are crucial in programming as they help you organize and reuse code efficiently. As we progress in the course, you'll see how understanding functions is vital for leveraging the full power of SciPy.
Creating Simple Functions
Let's quickly recall python functions, as we are going to use them a lot in this course.
In Python, you define a function using the def keyword, followed by the function name and parentheses (). Inside the parentheses, you can define parameters, which are inputs to the function. Let's start with a simple function that adds two numbers:
def add_numbers(a, b):defines a function namedadd_numbersthat takes two parameters,aandb.return a + bcalculates the sum ofaandband returns the result.- When you call this function with
add_numbers(3, 4), it will return7.
Let's now explore more complex functions.
Example: Quadratic Function
Here's how to define :
- This function calculates the value of a quadratic expression
x^2 + 4*x + 4. - The
**operator is used to denotexraised to the power of 2. - When you call this function with
quadratic_function(2), it will return16.
Example: Trigonometric Function
Let's define
np.sin(x)andnp.cos(x)use NumPy library functions to calculate the sine and cosine ofx.- The function returns the sum of the sine and cosine of
x. - When you call this function with
trigonometric_function(np.pi/4), it will return approximately1.4142.
