Python Syntax

Execute Python syntax

As we learned in the previous section, we can directly write and execute Python syntax in the command line:

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

Or create a python file on the server, use the .py file extension, and run it from the command line:

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

Python Indentation

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

In other programming languages, code indentation is only for readability, but indentation in Python is very important.

Python uses indentation to indicate code blocks.

Example

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

Run Instance

If indentation is omitted, Python will make a mistake:

Example

Syntax Error:

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

Run Instance

The number of spaces depends on the programmer, but at least one is required.

Example

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

Run Instance

You must use the same number of spaces in the same code block, otherwise Python will make a mistake:

Example

Syntax Error:

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

Run Instance

Python Variables

Variables in Python are created when they are assigned a value:

Example

Variables in Python:

x = 5
y = "Hello, World!"

Run Instance

Python does not have a command to declare variables.

You will learn in Python Variables Learn more about variables in this chapter.

Comments

Python has the function of commenting on code within documents.

Comments start with #, and Python presents the rest as comments:

Example

Python Comments:

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

Run Instance