A function takes an input (or none or many inputs) and returns an output. This is useful to organize code and make reuseable code. In this section, we will write some functions and see how they work!
A boolean variable in python is a variable that takes on the value True or False only. Not a number, not a string, but a truth value. You can use this in if statements to perform actions depending on the truth value.
Imagine you are writing code and find that you frequently need to check if a number is a multiple of 5. This is the perfect situation to use a function! A function is defined in the following way.
The keywords are "def" to define the function and "return" for the output. You can call a function whatever you want, as long as it is not a name used by python for something else. Letβs name our function and the inputs.
To check if we have a multiple of 5, we will see if there is a remainder when the number is divided by 5. Recall from the mini projects that % will tell you the value of the remainder. So we want a remainder of 0 when the number is divided by 5.
Thatβs it! That is our function! It will return True is the number we put in is a multiple of 5 and false oherwise. It does not print anything, so the following code will not show anything.
We could also use it in an if statement since it returns true or false. Suppose that if a number is a multiple of 5 that we want to add 2 to it. Then, we could write:
In chapter 1, you wrote code to solve one quadratic equation. In fact, you found only one real root of that equation. It is quite a bit to type to even find one root. That is the type of code that is useful to write as a function.
Recall that the solutions to a quadratic equation \(ax^2+bx+c=0\) are: \(x = \dfrac{-b \pm \sqrt{b^2-4ac}}{2a}\) The roots are real numbers as long as we take the square root of positive numbers. If \(b^2-4ac < 0\text{,}\) then we are taking the square root of a negative and the roots will be complex numbers.
Letβs say we just want real roots. Our function should test for real roots first. It is common to return something like "False" when the case does not work. That is what we will do here.
Due to the \(\pm\text{,}\) there are two roots. We will find each of these and then return a list of roots. So, we will need to define a list, find the roots, and then append them to the list. Finally, we will return the list.
There are many ways to improve this function. For example, if someone types 0 for a, we will have issues since we are dividing by a. You could put an error message in, or comment your code that a canβt be zero. We should also test that it correctly returns False when there are no real roots.
Write a function with three inputs that returns true if the third input is the product of the first two inputs and false otherwise. Check your function with two sets of inputs: (3,4,12) and (2,5,8).