🛠️ Scheduled Maintenance | We’ll be undergoing scheduled maintenance and upgrades between 00:00 PST Jan 26th until 00:00 PST Jan 28th. There may be brief interruption of services in that period. We apologize for the inconvenience.

×

# Combining Python Conditional Statements and Functions Exercise

Exercises 1 Question
/ / Combining Python Conditional Statements and Functions Exercise

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&lt;0:

return (&quot;Negative&quot;)

Similarly, add an IF statement that checks if the number is positive and returns an appropriate message.

def sign(num):

if num&lt;0:

return (&quot;Negative&quot;)

if num&gt;0:

return (&quot;Positive&quot;)

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&lt;0:

return (&quot;Negative&quot;)

if num&gt;0:

return (&quot;Positive&quot;)

return (&quot;The number is 0&quot;)

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!

Good job and check out the full range of exercise here!

## Earn your Data Science Degree

Expert instructions, unmatched support and a verified certificate upon completion!