There is no relevant multi day train pass. The Central Scotland pass might have worked, but it only gets as far as Markinch on the way to Leuchars for St Andrews, and the Spirit of Scotland won't be worth it on those trips.
So it's walk up point to point train tickets,
For Lothian transport (buses and trams) you need to look at what best suits the travel you intend to do- but probably the weekly capping.
If going soon be aware that the tram is currently still not serving Central Edinburgh and on to Leith/Newhaven after the fire, but terminating at West End, so the Airlink bus may be the best way to/from the airport depending where you are staying.
Also if aiming for best value, then on the days out I was having by train I wouldn't use any Lothian fares scheme (single fares, day rover or weekly capping) for those days- I would rather buy an Edinburgh plus bus ticket with my rail tickets (to any destination)- https://www.plusbus.info/edinburgh
To St Andrews don't buy a through ticket to St Andrews including the bus link from Leuchars. Buy a rail ticket day return to Leuchars, then on the bus a North East Fife Day Rider for £9.40.
That is the cheapest way to do it, if going by train.
If you go by bus from Edinburgh, which allows you to see much more of Fife and the coastal villages then the return fare is £12.80- a East Scotland Day Rider, all the way from Edinburgh to St Andrews (and beyond to Pitlochry, Dundee, Perth and Aberdeen, also Stirling via Dunfermline).