Industrial Training




Python Syntax

Execute Python Syntax

As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:


>>> print("Hello, World!")
Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:

C:\Users\Your Name>python myfile.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line.


Python uses indentation to indicate a block of code.


Example

if 5 > 2:
  print("Five is greater than two!")

Python will give you an error if you skip the indentation:


Example

Syntax Error:

if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, but it has to be at least one.


Example

if 5 > 2:
 print("Five is greater than two!") 
if 5 > 2:
        print("Five is greater than two!")

You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:


Example

Syntax Error:

if 5 > 2:
 print("Five is greater than two!")
        print("Five is greater than two!")

Python Variables


In Python, variables are created when you assign a value to it:

Example


Variables in Python:

x = 5
y = "Hello, World!"

Comments

Python has commenting capability for the purpose of in-code documentation.


Comments start with a #, and Python will render the rest of the line as a comment:


Example

Comments in Python:

#This is a comment.
print("Hello, World!")

Comments can be used to explain Python code.


Comments can be used to make the code more readable.


Comments can be used to prevent execution when testing code.


Creating a Comment


Comments starts with a #, and Python will ignore them:


Example

#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:


Example

print("Hello, World!") #This is a comment

Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code:

Example

#print("Hello, World!")
print("Cheers, Mate!")

Multi Line Comments


Python does not really have a syntax for multi line comments.


To add a multiline comment you could insert a # for each line:


Example

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:


Example

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")



Hi I am Pluto.