Python Python Basics (2015) Number Game App Squared

Aiden Colley
Aiden Colley
926 Points

I'm not sure where to start, need help...

I have an idea on what i need to do, I just can't seem to implement it into the correct syntax. the question asks to convert anything that can be converted to a integer to be converted, then squared otherwise square the string. This is what I have so far. You can see I really have no idea on what to do:)
def squared(yay):
    if yay == int:
        return yay*yay

1 Answer

Gabrielle Lamarche
Gabrielle Lamarche
8,586 Points

Hi Aiden,

There are a couple of strategies you could use for this example. "isinstance" is preferred in cases where you may be including inheritance as it will also check subclasses.

if isinstance(yay, int):
    return yay*yay

if type(yay) is int:
    return yay*yay

Here's a comparison I found quite helpful on StackOverflow:

isinstance(Vehicle(), Vehicle)  # returns True
type(Vehicle()) == Vehicle      # returns True
isinstance(Truck(), Vehicle)    # returns True
type(Truck()) == Vehicle        # returns False, and this probably won't be what you want.

I hope this helps!