The difference between syntax and semantics

The difference between syntax and semantics
Photo by Brett Jordan / Unsplash

If you've just begun programming, you might come across this word, "syntax." For simplicity, syntax is merely the grammatical rules of a programming language like Python. English also has a syntax, which is its rules of grammar.

Semantics, on the other hand, refers to the underlying meaning. If you know the difference between syntax and semantics, your programming journey would become easier. Let's look at it briefly.

Consider the following statements:

  1. Print the line "hello world" to the console
  2. print("hello world")
  3. puts "hello world"
  4. cout << "hello world";
  5. console.log("hello world")

They all look slightly different, but you can instantly recognize that they all print "hello world" to the console screen. Thus, semantically, they're equivalent, because they all mean the same. The difference between each of the statements is only the language (syntax).

The first is written in English, the second is Python, the third is Ruby, the fourth is C++, the fifth is JavaScript. This is why experienced programmers don't worry about the language too much, because you can express any idea in any of these languages.

When learning to code, you are given a line of code like puts "hello world" and told what it does in English. But you're never taught the reverse, which is coming up with an idea in English and then translating it into Python.

Let's look at an example of this:

Example:

Let's consider the following English statement:

Take a number from the user, and print the square of it

We can break this down as:

Take a number from the user
Calculate the square of it
Print the squared number

Now, we can translate each line into Python easily:

# Take a number from the user
number = input("Enter a number: ")

# Calculate the square of it
# (Of course, we'll have to convert the string into
#  a number first)
square = int(number)**2

# Print the squared number
print("The squared number is: ", square)

See? An easy way to get started with projects of your own is to write down steps in English, and then translate it piecemeal into Python (or any other language of your choice).

As you practice this more, you'll get to a point where you can do all of this mentally for small programs rather than physically writing things down.