MWZ

MINDWAREZONE

Python Syntax

Execute Python Syntax

Python syntax can be executed by writing directly in the Command Line:

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

You can also write your code in a Python file (ending with .py) and run it using the command line or terminal.  

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

Python Indentation

In Python, indentation means adding spaces at the beginning of a line of code.

Unlike many other programming languages where indentation is mainly used to make code easier to read, Python uses indentation to define blocks of code. This means indentation is a required part of Python syntax.

For example, the code inside an if statement, loop, or function must be indented so Python knows which statements belong to that block.

Incorrect indentation will cause Python to generate an error.

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

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

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

Syntax Error:

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

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:

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

Syntax Error:

Python Variables

In Python, a variable is created when you assign a value to it:

x = 5
y = "Hello, World!"
            

Python has no command for declaring a variable.

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:

Comments in Python:

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

Python Statements

A computer program is a collection of instructions that tell a computer what actions to perform.

In programming languages, these instructions are known as statements. Each statement performs a specific task when the program runs.

For example, the following statement displays the text "Python is fun!" on the screen:

print("Python is fun!")
            

In Python, a statement usually ends when the line ends. You do not need to use a semicolon (;) like in many other programming languages (for example, Java or C).  

Semicolons (Optional, Rarely Used)

Semicolons are optional in Python. You can write multiple statements on one line by separating them with ; but this is rarely used because it makes it hard to read:  

print("MindWareZone"); print("Welcome to MindWareZone"); print("Learn more tutorials")
            

However, if you put two statements on the same line without a separator (newline or ;), Python will give an error:  

print("Python is fun!") print("Really!")
            

Result:

SyntaxError: invalid syntax