Executing Python Syntax: Basics of Execution, Indentation, Variables, and Comments
Execute Python Syntax
Running Python Syntax
Python code can be executed in more than one way. One common method is typing instructions directly into the Python command line, where each line runs immediately after you press Enter.
For example, entering a simple instruction like:
"print(10 + 5)"
will instantly display the result in the terminal.
Another approach is creating a Python file using the .py extension and running it through the command line. This method is commonly used for larger programs and scripts. You write your logic inside the file and then ask Python to execute it.
Python Indentation
Indentation means the spaces added at the beginning of a line of code.
In many programming languages, indentation is only used to make code easier to read. In Python, indentation is required and directly affects how the program works.
Python uses indentation to group lines of code into blocks. For example, when using conditions or loops, indented lines belong to the same block.
A simple conditional example looks like this:
"if 10 > 3:"
" print("Ten is larger than three")"
If indentation is missing, Python will raise a syntax error because it cannot understand which lines belong to the condition.
The number of spaces used for indentation is your choice, but four spaces are commonly recommended. Whatever number you choose, it must be consistent within the same block.
Using different indentation levels inside the same block, such as mixing one space and several spaces, will result in an error.
Python Variables
In Python, variables are created automatically when you assign a value to a name.
For example:
"count = 12"
"message = "Python is easy to learn""
There is no need to declare the variable type explicitly. Python determines the type based on the assigned value.
Variables will be covered in more detail in a dedicated chapter later in this tutorial.
Comments in Python
Comments are used to explain code and make it easier to understand. Python ignores comments when running the program.
A comment starts with the # symbol, and everything after it on the same line is treated as a comment.
For example:
"# This line explains what the next instruction does"
"total = 25"
Comments are helpful for documentation, reminders, and improving code readability.