Python Syntax
Execute Python Syntax
Python syntax, as we learned on the previous page, can be carried out by typing directly in the Command Line.
>>> print("Hello, World!")
Hello, World!
Alternatively, you can create a python file on the server with the .py file extension and run it from the command line :
C:\Users\Your Name>python myfile.py
Python Indentation
The spaces at the beginning of a code line are referred to as indentation.
Where as indentation in code is only for readability in other programming languages, it is critical in Python.
In order to specify a code block, Python uses the indentation.
Example 1 :- With Indentation
if 5 > 2:
print("Five is greater than two!")
Output :-
Example 2:- Without indentation it gives syntax error :
if 5 > 2:
print("Five is greater than two!")
Output :-
print("Five is greater than two!")
^
IndentationError: expected an indented block
Example 3 :- As a programmer, you decide number of spaces to use, but there must be at least one :
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Output :-
Five is greater than two!
In the same coding block, you have to use the same number of spaces, otherwise, Python will make the mistake :
Example 4:- Syntax Error with different number of spaces in a code block :
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Output :-
print("Five is greater than two!")
^
IndentationError: unexpected indent
Related Links
Python Variables
When a value is assigned to Python, variables are created :
Example :- Variables in Python :
x = 5
y = "Hello, World!"
print(x)
print(y)
Output :-
Hello, World!
Python has no command for expressing a variable.
Related Links
Comments
For the purpose of in-code documentation, Python has the capacity to comment.
Python will output the rest of the line as a comment if it begins with # :
Example :- Comments in Python :
#This is a comment.
print("Hello, World!")
Output :-