Python is known for its clean and simple syntax, making it an easy-to-read and write programming language. One of Python's unique features is its reliance on indentation to define code blocks, unlike many other languages that use braces or keywords.
Python syntax is designed to be straightforward and human-readable. Here are some basic rules:
:
) to indicate the start of an indented block.#
symbol.
# Example 1: Simple Python syntax
print("Hello, World!") # This prints a greeting message
Output:
Hello, World!
Python uses indentation to define blocks of code. Indentation refers to the spaces at the beginning of a line. Consistent indentation is required, and mixing tabs and spaces is not allowed.
# Example 2: Proper indentation in Python
if True:
print("Condition is True")
print("This is inside the block")
print("This is outside the block")
Output:
Condition is True This is inside the block This is outside the block
Improper indentation will result in an error.
# Example 3: Incorrect indentation
if True:
print("This will cause an IndentationError")
Error:
IndentationError: expected an indented block
Python uses additional indentation for nested blocks of code, such as loops and conditionals.
# Example 4: Nested indentation
for i in range(3):
print("Outer loop iteration:", i)
for j in range(2):
print(" Inner loop iteration:", j)
Output:
Outer loop iteration: 0 Inner loop iteration: 0 Inner loop iteration: 1 Outer loop iteration: 1 Inner loop iteration: 0 Inner loop iteration: 1 Outer loop iteration: 2 Inner loop iteration: 0 Inner loop iteration: 1
Functions in Python require consistent indentation for their code blocks.
# Example 5: Function with proper indentation
def greet(name):
print("Hello,", name)
print("Welcome to Python!")
greet("Alice")
Output:
Hello, Alice Welcome to Python!
Python's syntax and indentation rules contribute to its readability and simplicity. By following these rules and best practices, you can write clean and maintainable Python code.