Skip to main content

Execute Python Syntax

There are two ways to run Python syntax: type it straight into the Command Line, or save it on the server in a file with the .py extension and run that file from the Command Line.

Command line execution

main.py
>>> print("Hello, World!")
Hello, World!

Run a Python file

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

Python Indentation

The spaces at the start of a line of code are called indentation.

Other languages use indentation only to make code easier to read. Python is different and depends on it, because indentation is how it marks a block of code.

Example

Prompt
Use an if statement to check if 5 is greater than 2, and print "Five is greater than two!" with correct indentation.
Output: complete Python program

Syntax Error

Leaving out the indentation makes Python report an error:

Prompt
Demonstrate a Python indentation error by writing an if statement without indenting the print line. This code should produce a syntax error.
Output: complete Python program

Different spaces

You decide how many spaces to use. Four is the most common choice, and one is the minimum.

Prompt
Show two if statements checking if 5 > 2, one using one space for indentation and one using four spaces, both printing "Five is greater than two!".
Output: complete Python program

Mixed indentation error

Within a single block of code, the number of spaces has to stay the same. If it changes, you get an error:

Prompt
Demonstrate a Python error caused by mixing different numbers of spaces in the same code block. Use an if statement with one print indented by one space and another by four spaces.
Output: complete Python program

Python Variables

You don't need a special command to declare a variable in Python. It comes into existence as soon as you assign it a value.

Example

Creating and printing variables:

Prompt
Create a variable x with value 5 and a variable y with value "Hello, World!", then print both variables.
Output: complete Python program

Comments

Python lets you document your code with comments. A comment begins with #, and everything after it on that line is ignored.

Example

A comment in Python:

Prompt
Write a comment followed by printing "Hello, World!".
Output: complete Python program