Object attribute error when assigning material
In the example given, you're expecting an active object, (bpy.context.object) when there are none.

Its possible to have selected objects, but nothing active.

In this case you don't even need to have an active object. You can assign the material directly to the object, there is no need to selecting it before:

# create the material
mat = bpy.data.materials.new('MaterialName')
mat.diffuse_color = (1.0,0.0,1.0)
mat.diffuse_shader = 'LAMBERT'
mat.diffuse_intensity = 1.0

# get the object
obj = bpy.data.objects['Cube']

# get the material
mat = bpy.data.materials['MaterialName']

# assign material to object
obj.data.materials.append(mat)

# or overwrite an existing material slot via index operator
obj.data.materials[0] = mat