Skip to content Skip to sidebar Skip to footer

Python 3: TypeError: Unsupported Operand Type(s) For +: 'float' And 'str'

Can somebody tell me why i get the error code: TypeError: unsupported operand type(s) for +: 'float' and 'str' while True: c = input('Gib die Temperatur in Grad Celcius

Solution 1:

You are misplacing the parentheses when you attempt to transform the result of convert_to_temperature(c) which returns a float to a string. This is your line which is incorrect, because str() is being applied to convert_to_temperature(c) + " Kelvin." which if you check the individual types:

print(type(convert_to_temperature(c)))
print(type(" Kelvin."))

Returns:

float
str

Therefore the str() must be applied only to the output of convert_to_temperature(c):

print("Das sind " + str(convert_to_temperature(c)) + " Kelvin.")

Allowing for a concatenation of strings via the + operator.


Solution 2:

I think you missed the get_temperature() function header (supplied here). And the last line you can modify to make it work: 

def get_temperature():
        while True:
            c = input("Gib die Temperatur in Grad Celcius ein:  ")
            try:
                c = float(c)
                return c
        
            except ValueError:
                print("Das ist keine gültige Angabe für eine Temperatur")
    
    
    
    
    if __name__ == "__main__":
        c = get_temperature()
        print(f"Das sind {convert_to_temperature(c)} Kelvin.")

Post a Comment for "Python 3: TypeError: Unsupported Operand Type(s) For +: 'float' And 'str'"