Python Syntax Execution Methods

Learn the two primary ways to execute Python syntax: through the command line interface (CLI) and by writing code directly. Explore an example of using the CLI to print a simple message.



Python Syntax

You can execute Python syntax in two primary ways:

Command Line:You can write Python code directly in the command line interface (CLI).

Example:

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

Hello, World!
      

Python File: Alternatively, you can create a Python file with a .py extension and run it from the command line.

Shell

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

Python Indentation

Indentation in Python is crucial as it indicates a block of code. Unlike other programming languages where indentation is only for readability, Python uses it to define the structure and flow of the code.

Example

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

If you skip the indentation, Python will raise an error.

Example (with Syntax Error)

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

The number of spaces for indentation is up to you, but the common practice is to use four spaces. However, it must be consistent within the same block of code.

Example

if 5 > 2:
    print("Five is greater than two!")  # Four spaces
if 5 > 2:
        print("Five is greater than two!")  # Eight spaces
  

Inconsistent indentation within the same block will cause an error.

Example (with Syntax Error)

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

    File "demo_indentation2_error.py", line 3
      print("Five is greater than two!")
      ^
  IndentationError: unexpected indent
      

Python Variables

Variables in Python are created when you assign a value to them. There's no need for an explicit declaration.

Example:

x = 5
y = "Hello, World!" 
Output

5
Hello, World!
      

Python has no command for declaring a variable.

You will learn more about variables in the Python Variables chapter.

Comments

Python allows you to include comments for in-code documentation. Comments start with a # and everything following it on the line is ignored by Python.

Example:

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

Hello, World!