
Syntax is the way we write code in a particular programming language. There are many programming languages available to us for computing with special features and more. Getting familiar with the syntax of programming languages are important to avoid errors, increase readability and efficiency of the code.
Every programming languages have certain differences in syntax which must be monitored and used carefully. In this article, we are about to learn more about syntax, common practices to avoid syntax error in programming.
In Python, you do not need to explicitly mention the data types; however in C++ it is important to declare the data type along with the variable. Let us understand this with an example.
| #Example of Python Syntax x = 15 y = 3.14 name = “Ankit” #Example for C++ Syntax int x = 10; float y = 3.14; |
Syntax differentiates one programming language from another. There is always a syntax difference between programming languages. Writing syntax correctly enhances code readability, maintainability, and efficiency.
|
| def add (a, b): # Colons are used as delimiters return a + b |
| #C++ statements
int x = 0; #Statements in C++ for (int i = 0; i<=10; i++){ x++; cout <<(“The value of x is”, x); |
| #Python Indentation Block
if x > 0: # Python block
print("Positive number")
#CPP Block if (x > 0) { // C++ block cout << "Positive number" << endl; } |
| Syntax | Semantics |
| Syntax refers to the rules and structure for writing code in a programming language. | Semantics refers to the meaning or logic of the code. |
| It deals with how code is written, mainly its grammar and format. | It deals with what the code does mainly its behavior and execution. |
| Syntax errors occur when the code violates grammatical rules (e.g., missing colons, braces, etc.). | Semantic errors occur when the code runs but produces incorrect results or behavior. |
| Python: if x > 0 (missing colon) | Python: x = "5" + 3 (incorrect meaning; mixing string and integer). |
| Syntax ensures the code is well-formed and can be parsed by the compiler/interpreter. | Semantics ensures the code behaves as intended and produces the correct output. |
| Like grammar in a language it ensures sentences are structured properly. | Like the meaning of a sentence it ensures the sentence conveys the correct idea. |
| #Mistake in Delimiters in Python print (“Hello World! ❌ # Corrected Format ✅ print (“Hello World” ) #This will execute successfully |
| # Incorrect Format with missing Colons (:) if x > 5 ❌ print (“Yes”) #Corrected Format ✅ if x>5: print (“Yes”) |
| #Using uppercase in Print instead of print will raise an error. Print (“Hello World!) ❌ print (“Hello World!”) ✅ |
| if x > 5: print("X is greater than 5") # Missing indentation ❌ |
| def = 10 # 'def' is a reserved keyword in Python. ❌ |
| #Missing Semicolon int x = 10 ❌ #Semicolon int x = 10; ✅ |
| def add(a, b): sum = a + b # Missing 'return sum' ❌ |