Python - Syntax

25-Mar-2024

Python Syntax is the grammar of the language, dictating how we write code for clarity and functionality. It's the rulebook for error-free programming.

Python Syntax : The Code Rulebook


Python syntax is the set of rules that dictate how we structure and write Python code. Similar to grammar in a language, it ensures our instructions make sense to the computer.



Indentation :


In Python, indentation is more than mere formatting—it's a crucial element that defines the structure and execution flow of your code. Unlike other programming languages that use braces to encapsulate blocks of code, Python relies entirely on indentation. Here's why it matters:

Consider this example :




if 7>3 : print("Seven is greater than Three")


Output :




Seven is greater than Three


If the indentation is skipped, Python will report an error. Example :




if 7>3 : print("Seven is greater than Three")



Output :



File "test.py", line 2 print('Seven is greater than Three') ^ IndentationError: expected an indented block after 'if' statement on line 1


You, as a programmer, have flexibility in choosing the number of spaces for indentation in Python. The most common practice is to use four spaces, but it must be at least one. It's crucial to maintain consistency within the same code block; otherwise, Python will raise an error.

Example :



if 7>3 : print("Seven is greater than Three") print("Three is smaller than Seven")


Output :




File "test.py", line 3 print("Two is smaller than Seven") TabError: inconsistent use of tabs and spaces in indentation









Comments