datacraftworks.com

Python Code Block Types

| Code Block | Definition | Syntax Example | Explanation | |————————-|————————————————————————————————————|————————————————————-|——————————————————————————————————————-| | Function Block | A block of code that defines a function. | def greet(name): | Functions start with def, followed by an indented block. | | | | ` print(f”Hello, {name}”) | | | **Class Block** | A block of code that defines a class. | class MyClass: | Classes start with class, followed by an indented block. | | | | def method(self): | | | | | pass | | | **If-Else Block** | A block of code that executes conditionally based on a condition. | if x > 0: | Uses if, elif, and else keywords, each followed by a colon and an indented block. | | | | print(“Positive”) | | | | | elif x == 0: | | | | | print(“Zero”) | | | | | else: | | | | | print(“Negative”) | | | **For Loop Block** | A block of code that iterates over a sequence. | for i in range(5): | The for statement is followed by an indented block. | | | | print(i) | | | **While Loop Block** | A block of code that repeats as long as a condition is true. | while x > 0: | The while statement is followed by an indented block. | | | | x -= 1 | | | **Try-Except Block** | A block of code that handles exceptions (runtime errors). | try: | Begins with try, followed by one or more except blocks. | | | | result = 1 / x | | | | | except ZeroDivisionError: | | | | | print(“Cannot divide by zero”) | | | **With Block** | A block of code that simplifies resource management (e.g., opening files). | with open(“file.txt”) as f: | The with statement is followed by an indented block. | | | | content = f.read() | | | **List Comprehension** | A concise block for creating lists in a single line. | squares = [x2 for x in range(10) if x % 2 == 0] | List comprehensions are single-line blocks enclosed in brackets. | | **Dictionary Comprehension** | A concise block for creating dictionaries in a single line. | squares_dict = {x: x2 for x in range(5)} | Dictionary comprehensions are single-line blocks enclosed in braces {}. | | **Docstring Block** | A block of code that provides documentation for a module, class, or function. | def greet(): | Docstrings are enclosed in triple quotes ”””. | | | | “"”This function greets the user.””” | | | | | print(“Hello”)` | |