Python Python Basics (2015) Number Game App Squared

Hey guys, stuck on this one again. More details in the description.

so the original went like.... 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.)

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
    num = input("please enter a number or word ")
    try:
        return int(num)**2
    except:
        return "num" * len(num)

1 Answer

Jennifer Nordell
MOD
Jennifer Nordell
Treehouse Moderator

Hi there! I feel like you probably do understand the instructions and what they want pretty well. However, in these challenges it's a great idea to not do anything they don't explicitly ask for. This function is going to take in a piece of data from Treehouse. It could be a number, it could be a string that can be converted to an integer like "42", or it could be a string that can't be converted to an integer like "hello". On your very first line, you are overwriting the value that they are sending in with a prompt to the user. But there is no user on the other end.

So that line needs to be deleted. Once you've done that, there will only be one slight problem. It's in your very last line. Let's say I sent in the word "hello" which can't be converted to an integer. Because "hello" has a length of 5, I would expect to get back hello 5 times like "hellohellohellohellohello".

In your last line, you have "num" in double quotes which makes it a string. No matter what I send in right now, it's going to print "num" the number of times that is equal to the length of what I send in. If I were to send in "cat" right now it will return "numnumnum" because "cat" has a length of 3 and it is printing "num" 3 times. The solution is to remove the quotation marks from around "num":

return num * len(num)

Hope this helps! :sparkles:

Ohh Jennifer, you are a great teacher, i cannot thank you enough. I loved your patience in explaining and taking it right from the top. Simply the best answer i've ever gotten. THANKS ONCE AGAIN.