How to change a project variable using Python?
Look at QgsExpressionContextUtils (https://qgis.org/api/classQgsExpressionContextUtils.html). The method you need is QgsExpressionContextUtils.setProjectVariable, e.g.
QgsExpressionContextUtils.setProjectVariable('myvar','hello world')