Understanding Python Syntax
Executing Python Syntax
In Python, syntax can be executed directly via the command line interface, making it especially accessible for beginners:
>>> print("Hello, World!")
Hello, World!
Alternatively, you can create a Python script using the .py
extension and run it via the command line:
C:\Users\Your Name>python myfile.py
Python Indentation
Indentation in Python is not just for visual organization; it is a syntactical requirement. Unlike other programming languages where indentation is optional, Python uses indentation to define code blocks.
Correct example:
if 5 > 2:
print("Five is greater than two!")
Incorrect example (causes syntax error):
if 5 > 2:
print("Five is greater than two!")
The number of spaces used is flexible (commonly four), but consistency within the same block is essential to avoid errors.
if 5 > 2:
print("Correct indentation")
if 5 > 2:
print("Also valid, if consistent")
Incorrect example (mixed indentation):
if 5 > 2:
print("First line")
print("Second line")
Python Variables
Variables in Python are created upon assignment. There is no need to declare a variable type beforehand.
x = 5
y = "Hello, World!"
Python automatically recognizes the data type based on the assigned value. You’ll explore this further in the Python Variables chapter.
Writing Comments in Python
Comments in Python start with the #
symbol. Everything after this symbol on the same line is treated as a comment and ignored during execution.
# This is a comment
print("Hello, World!")
Comments are essential for making your code understandable to others and yourself.