'float' object has no attribute...(beginner)

Hello there,

I have written a simple function to find the area of a square:

def area_of_square():
side_length = float(raw_input("Length in cm: "))
area = side_length ** 2
if side_length.isalpha():
print “this is not a number”
print area

When I attempt to run this, after I input the “side_length” I get the error stating: ‘float’ object has no attribute ‘isalpha’.

If I get rid of the ‘float’ in front of the ‘raw_input’, it states: unsupported operand types for ** or pow(): ‘unicode’ and ‘int’
^ I am not sure what this even means.

Is there a way to solve this? I would like it to print “this is not a number” if the user inputs a letter and print out the area if it is.

Thanks in advance :octopus:

Hey there!

isalpha() is a string method as far as I know. If you want to test if it’s a string or an integer or a float you could do a conditional for type ==

Remember to format your code with the </> in the future :slight_smile:

1 Like

Hey there @core6539010994 :grinning:

@toastedpitabread is correct that .isalpha() is a string method, hence your error.

There are a few different ways you could do this, though personaly I would use a try/except statement, which is practicly a way of rerouting your code if an error is thrown.

For instance:

n = raw_input()   #n is equal to the users value

try:           #The try statement will attempt to run the followin code
  n = float(n)
  print n

#The except statement can bypass the above lines of code if they throw
#the error being named, in this case ValueError.

except ValueError:
  print "This is not a valid number"
  #and if that error is thrown it runs the code within the except block