Python Python Basics Functions and Looping Raise an Exception

Victor A Hernandez
Victor A Hernandez
1,957 Points

How to raise an Exception. What I'm doing wrong with my coding? This is my code:def suggest product_idea: return pro

suggestinator.py
def suggest product_idea:
    return product_idea + "inator"
if product_idea <3:
    raise ValueError(" ")

3 Answers

Victor A Hernandez
Victor A Hernandez
1,957 Points

Thanks Cameron, I appreciate you help.

Cameron Childres
MOD
Cameron Childres
Treehouse Moderator 11,543 Points

Hi Victor,

Some things to point out:

  • The parentheses originally included in the function are necessary to set the parameters, don't remove them
  • A string and an integer can't be compared with the ">" operator, so you'll need to use the len() function on product_idea to convert it to a number representing its length
  • Your "if" statement is outside of the function -- we want the error to be raised as part of the function, before anything is returned

I hope this helps steer you in the right direction! Let me know if you need any further assistance.

Victor A Hernandez
Victor A Hernandez
1,957 Points

Honestly, I don't get the idea.

Cameron Childres
Cameron Childres
Treehouse Moderator 11,543 Points

Okay, I'll go through the code from the challenge with my points from above in mind:

def suggest(product_idea):
    return product_idea + "inator"

This defines a function that will return whatever we pass to it plus "inator". The challenge wants us to raise an error if the string passed to it is shorter than 3 characters. We want it included in the function, and we want to raise the error before the function returns the result. Since code runs from top to bottom we'll put it here:

def suggest(product_idea):
    #raise error here
    return product_idea + "inator"

The error needs to be raised only when the amount of characters in product_idea is less than 3. An "if" statement is perfect for that, but if we try to compare a string to a number it won't work. We need to convert the string to a number representing its total amount of characters (or length) which is done with the function len():

def suggest(product_idea):
    if len(product_idea) < 3:
        raise ValueError
    return product_idea + "inator"