Welcome back to the Python tutorial series at CipherTrick.com! Having covered Python basics, we’re now ready to deep-dive into Python’s syntax. This tutorial will walk you through Python’s syntax essentials, helping you write clean and readable code.

Part 1: Python Indentation

One distinctive aspect of Python syntax is the use of indentation to define code blocks. Where many languages use curly braces {} or keywords like begin and end, Python uses indentation. This requirement makes Python code clean and easy to read. A block of code (like the body of a function or a loop) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.

for i in range(5):
    print(i)  # This statement is part of the for loop because it's indented
print("Done")  # This statement isn't part of the for loop because it's not indented

Part 2: Python Comments

Comments in Python start with the hash character, #, and extend to the end of the physical line. They are used to explain code and are not interpreted by Python. Use comments judiciously to make your code more understandable.

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

Part 3: Python Variables and Naming Rules

In Python, variables are declared by simply assigning a value to a name. Variable names are case-sensitive and can contain alphanumeric characters and underscores. They must start with a letter or an underscore.

x = 5
_my_variable = "Hello, World!"

Part 4: Python Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue.

total = 1 + \
        2 + \
        3

Alternatively, statements contained within the [], {}, or () brackets do not need to use the line continuation character.

numbers = [1,
           2,
           3]

Part 5: Python Importing Modules

Python’s import statement is used to import modules into your current program, providing access to additional functions and classes.

import math
print(math.pi)  # Prints the value of pi

Conclusion

Understanding Python’s syntax is fundamental to becoming proficient in Python. Its simplicity and readability are just a couple of the reasons Python is so popular. Keep practicing, and stay tuned for our next post where we’ll dive deeper into Python’s fascinating world!