Alexandra CiorraPython Web Development Techdegree Student 796 Points
I'm not sure how to finish the second part? Is my first correct?
I am trying to figure this our but most of the time i need a boost to understand. Is my firs part correct? If not where did I go wrong? How do I finish the else?
def squared (num): try: num=(int(input(num*num) else: return len(num) # EXAMPLES # squared(5) would return 25 # squared("2") would return 4 # squared("tim") would return "timtimtim"
Hey Alexandra! Your slightly off track here. I would suggest watching the previous video again because it dosent seem you have picked up on the try and except idea. However in the comments there are examples of what the function is expecting to have returned with different kinds of inputs. While your code is not finished it still has a couple of problems. First is that your trying to int(input(num)).. There should be no input what so ever in this function. What the challenge says is: It will provide you with an unknown string or number, you have chosen to store this number or string in the variable "num". Now it wants you to try to turn this number into an integer, if you can do that return the square of that integer, if not return the legnth of the string multiplied by the string. Here is the code:
def squared(num): #Here your saying that the string or number should be stored in the variable num try: #Here your asking the computer to try to do the following num = int(num) #Here were trying to turn the num variable into a string, and store it in the variable "num" return num ** 2 #Here were returning the square of that number except ValueError: #If the variable cannot be turned into a integer it will spit a ValueError, and will do what comes after this code return len(num) * num #Here were telling it to return the length of the string, multiplied by the string
If the last part is confusing, basicly if we have the string "test" and say "test" * 3, we will get "testtesttest". And the len() function allows us to find the len of a string, and return that length as an integer. Hope this helps but please feel free to write back if you need more help!