Syntax vs semantics: what’s the difference?

This is a subject that many programmers get confused about.  The difference isn’t really a difficult concept, it’s just that it’s not explained to programmers very frequently.  Let’s consider a snippet of a poem by Jeff Harrison:

know-bodies, devoted we to under-do for you
every Sunday-day of dressy morning, black pond,
sky’s germs, chairs’ ponds – prove it, stain!
us, rain-free & orphaned, we’re living laboratories
This is from Dart Mummy & The Squashed Sphinx.  If you haven’t figured it out, this text is generated by a computer.  And it uses the same techniques that a lot of spammers use.  What’s most interesting about this is that it’s grammatically correct.  For instance, “prove it, stain!” is a perfectly valid English sentence.  The problem is just that it’s meaningless.  Thus, we can say that the above poem is syntactically correct but has no meaning semantically.
Programming languages are similar in concept.  Consider the following Python snippet:
The above code is obviously incorrect.  It uses variables that haven’t been declared yet.  Therefore, it is semantically incorrect.  But it is a syntactically valid Python program.
In the same manner, we can say that these two snippets of code are identical semantically although they definitely have very different syntax:
python
def f(x):
return x + 1
rawplus1.py hosted with ❤ by GitHub
ocaml
let f x = x + 1
rawplus1.ml hosted with ❤ by GitHub
Therefore, we can define these terms like this:
 * syntax – A set of rules for specifying a program
 * semantics – The meaning behind that program