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.
Example: Exponential Function
Let's see another example – a definition of
np.exp(x)computes the exponential ofx,e^x, using the NumPy library.- The function then subtracts
3*xfrom the exponential and returns the result. - When you call this function with
exponential_function(1), it will return approximately-0.2817.
Example: Logarithmic Function
Here is your last example. Let's define
np.log(x)computes the natural logarithm ofx.- The function checks if
xis positive, as the logarithm is undefined for non-positive values, and if not, it returnsNone. - When you call this function with
logarithmic_function(2), it will return approximately1.6931.
Summary and Practice Preparation
In this lesson, you learned how to define, test, and use functions in Python. You explored different types of mathematical functions and saw how to implement them using Python's syntax. Understanding these principles is crucial as functions will be a cornerstone for optimizing mathematical problems with SciPy.
Now, as you progress to the practice exercises, remember to apply these concepts by experimenting with various function definitions. Test them with different inputs to solidify your understanding. Happy coding, and enjoy the journey of exploring optimization with SciPy!
