square of a number
This challenge is similar to an earlier one. Remember, though, I want you to practice! You'll probably want to use try and except on this one. You might have to not use the else block, though.
Write a function named squared that takes a single argument.
If the argument can be converted into an integer, convert it and return the square of the number (num ** 2 or num * num).
If the argument cannot be turned into an integer (maybe it's a string of non-numbers?), return the argument multiplied by its length. Look in the file for examples.
Above is the challenge, could not get the right answer please help me out,
# EXAMPLES # squared(5) would return 25 def squared(num): try: int(num) except valueError: print("thats not a number") else: print(num**2) # if num = int(number): # return(num**2) # else: # print(num**2) # squared("2") would return 4 # squared("tim") would return "timtimtim"
Dave HarkerPro Student 15,508 Points
# Write a function named squared that takes a single argument. def squared(num): # done, good. # If the argument can be converted into an integer, convert it and # return the square of the number (num ** 2 or num * num). try: # it's good you're testing it here, but why not just return here too? # perhaps try returning (int)num ** 2 directly here int(num) # we don't care at this point why type of exception is thrown, just that it is. But either way :) except ValueError: # if it failed casting it means we're here and it's not a number # so let's just return num * len(num) at this point, then we don't need an else print("thats not a number") #return here instead of print # an else isn't necessary anymore because the requirements are met and # all scenarions are dealt with already :) else: print(num**2)
Thought I'd just put the reasoning in comments.
You're almost there, keep going
Hope that helps