Setting the Target ID on a Taxonomy Reference Field in Drupal

Recently on a Drupal website, I was tasked with adding a taxonomy reference field to a content type. This taxonomy reference field replaced an existing select list. I was also tasked with writing a script to programmatically assign the value of the existing select field to the new taxonomy reference field.

But how do you programmatically set the value for a taxonomy reference field? It should be pretty straightforward and usually is. Most examples you find online use one of these two methods: