Syntax is basically the grammar of a programming language. Basically, how statements and keywords are structured. Python Syntax
Python is an easy to learn, powerful programming language. With Python, it is possible to create programs with minimal amount of code.
Here is a simple Python code that you can use to display the message “Hello World” in Java and Python
Example :
class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
print("Hello World")
greet = "Hello World" # Variable assignment
print(greet)
Indentation ?
For the same reason, Python needs indentation to make things easier to read.
Indentation(spaces) is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc., is defined within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors.
Example of indentation Error:
Skipping indentation
if 1 < 2:
print("true")
Output:
With indentation
if 1 < 2:
print("true")
true
Where to Indent:
You will need to indent after these 11 Python keywords:
if, else, elif
for, while
def
class
try, except, finally
with
Indentation Rule-1:
If you use a colon sign at the end of a line, you will need to indent the following line/lines.
In the code below, you have a colon after the second line. That’s why the third line is indented.
marks = 35
if marks < 35:
print("you are not Qualified")
If you don’t indent the line after the colon, you will get an indentation error.
marks = 35
if marks < 35:
print("you are not Qualified")
Indentation Rule-2:
If you have multiple lines inside the if block, all the lines will need to be indented. And the indentation has to be the same.
marks = 35
if marks < 35:
print("you are not Qualified")
print("Better luck next time")
Indentation Rule-3:
Regardless of your current level of indentation, if you write a colon at the end of the line, you will need to indent.
- Similar to Grammar rules in English each programming language has a unique set of rules. These rules are called the Syntax of a Programming Language.
- Indentation(spaces) is necessary for Python. It specifies a block of code.