Combining Conditional Statements and Functions Exercise:
Define a function that will determine whether a number is positive or negative.
The tutorials you may need: Learning How to Use Conditionals in Python, An Introduction to Python Functions
While this exercise looks like a simple ‘define a function’ one, it actually involves knowing a little about conditionals too. You can also check how to combine conditional statements and functions in the above tutorials.
We start by defining a function that takes a single numerical parameter. We add an IF statement that would then check if the number is negative and return the appropriate message. Remember to indent before calling the return function, so this only happens when the condition of the IF statement is satisfied.
def sign(num): if num<0: return ("Negative")
Similarly, add an IF statement that checks if the number is positive and returns an appropriate message.
def sign(num): if num<0: return ("Negative") if num>0: return ("Positive")
Remember that returning a value exits the entire function, so we do not need any additional ‘ELIF or ‘ELSE’ statements in case the number is neither positive nor negative. We simply add another return statement stating the number is 0 and we are done with our function. Make sure the last return statement is not indented under either of the preceding if-statements.
def sign(num): if num<0: return ("Negative") if num>0: return ("Positive") return ("The number is 0")
To test our work, we can call the function several times with different values to ensure we correctly covered all possible scenarios.
And that’s the end of this exercise. A short one – but enough to test your ability to combine functions and conditionals!
If you want to go a step further and learn more about conditional statements and functions, take our Introduction to Python course.