Basic Syntax
In programming, syntax refers to the set of rules and conventions that dictate how programs written in a programming language should be structured. Python has the most easy and readable syntax. It closely resembles English Language. It is an excellent choice for beginners because of its easy syntax.
Note: Whenever you write your python program, always save it with the extension .py, like myFirstProgram.py
Indentation and spaces
Unlike other programming languages, which uses braces and other symbols to separate different blocks of code like function, loops etc, python uses indentation.
Explanation
In this code, we can see that in the third line, there is a space in the begining. This is the indentation. In the example above, the lines of code indented under the if statement form a code block that is executed if the condition is true. All the lines which have same space in starting as third line, those lines will be the part of if statement. The line that is not indented is not part of the if block and is executed regardless of the condition. But if there is no need to indent and you still indent the code, you will get error. Indentation is necessary in python. If your code is not indented correctly, you will get error.
Indentation Error and Example
In the above example, you will get error because there is a space in the start of fourth line. Third line is not the part of if statement. All the lines of the same block will be intended on the same level.
Example
Now in this example, we see that the fourth line is at the same level of indentation as that of if statement, therefore it will be executed separately as it is not the part of if statement.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP