Check if material exists through python?

I’m trying to add a material to an object, if the material name already exists but isn’t assigned, have it assign that material while deleting any other slots. I just want that assigned material.

Here is what I have right now, it works but I would like to have a cleaner way of doing this.

import bpy


ob = bpy.context.active_object
# Delete all materials
C = bpy.context
for i in range(0,len(C.object.material_slots)):
    C.object.active_material_index = 0
    bpy.ops.object.material_slot_remove()
        
# Get material
mat = bpy.data.materials.get("rustymetal")

#if it doesnt exist, create it.
if mat is None:
    # create material and assign
    mat = bpy.data.materials.new(name="rustymetal")
    ob.data.materials.append(mat)
    #Remove all materials again, material already exists, so it can be linked.
    for i in range(0,len(C.object.material_slots)):
        C.object.active_material_index = 0
        bpy.ops.object.material_slot_remove()
#otherwise
else:
    #get material
    mat = bpy.data.materials.get("rustymetal")


#assign material
ob.data.materials.append(mat)

I use this function

def crear_material(name, color):    if name in bpy.data.materials:
        print("the color existe: "+ name+ "; changing...")
        index = posicion_material(name)
        mat = bpy.data.materials[index]
        mat.diffuse_color = color
        mat.type = 'SURFACE'


    else:
        
        try:
            mat = bpy.data.materials.new(name=name)
            mat.diffuse_color = color
            mat.diffuse_intensity = 1
            mat.use_shadeless = True
            mat.type = 'SURFACE'


            print("color " + name+" was created")
        except:
            print("error creating color  " + name)