Here is the code which is working for me:
urlWithParams = 'type=xyz&url=https://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857'
rlayer = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms')
if rlayer.isValid():
QgsProject.instance().addMapLayer(rlayer)
else:
print('invalid layer')
and result is:
like in an old discussion: Adding a Tiles/wms? (openStreetMap) layer with python in QGIS