My Python Learning Diary 2

Below are some common formatting considerations in Python programming, particularly related to syntax structures and code indentation.

📝 Summary of Python Formatting Considerations:

1. Colon (:

In Python, the colon<span>:</span> is very important as it marks the beginning of a control structure. It typically appears in places such as conditional statements, loops, and function definitions.

  • if statements require a colon:
    if age &gt;= 18:  # The colon is mandatory
        print("You are an adult")
  • else and elif also require a colon:
     if age &lt; 18:
      print("You are a minor!")
    elif age &lt; 30:   # A colon is also needed after elif
      print("You are a young person!")
    else:   # A colon is also needed after else
      print("You are an adult!")
  • for and while loops require a colon:
    for i in range(5):  # A colon is needed after the for loop
        print(i)

  • Function definitions:
    def greet(name):  # A colon is also needed after the function definition
        print(f"Hello, {name}!")

2. Indentation

  • • Python uses indentation to indicate code blocks, rather than using <span>{}</span> curly braces. All code at the same level must be indented with the same number of spaces, generally using 4 spaces for indentation.

    Example:

    if age &gt;= 18:  # Indentation starts a code block after if
        print("You are an adult")
    else:
        print("You are a minor")
    • • If the indentation is inconsistent, Python will raise an <span>IndentationError</span>.

3. Function Definitions

  • Function definitions require the use of def, followed by a colon <span>:</span>.
    def greet(name):  # A colon is needed after def
        print(f"Hello, {name}!")  # Indentation for the function body
    • The function body must be indented, and the code blocks of the same function must use the same indentation.

4. Symbol Formatting for Collection Types like Lists, Dictionaries, and Tuples

  • List (list):
    fruits = ["apple", "banana", "cherry"]
    • • Represented with square brackets <span>[]</span>, with elements separated by commas.
  • Dictionary (dict):
    person = {"name": "Linda", "age": 25}
    • • Represented with curly braces <span>{}</span>, with key-value pairs connected by colons <span>:</span> and separated by commas <span>,</span>.
  • Tuple (tuple):
    coordinates = (10, 20, 30)
    • • Represented with parentheses <span>()</span>, with elements separated by commas <span>,</span>.

5. Comments

  • Single-line comments: Use <span>#</span> to mark, and the part after the comment will not be executed.
    # This is a comment
    x = 5  # Comments can also be here
  • Multi-line comments: Can be enclosed with <span>"""</span> or <span>'''</span> to surround the comment content.
    """
    This is a multi-line comment
    Surrounded by three double quotes or single quotes
    The content will be ignored
    """

6. Using Strings

  • Strings can be enclosed with single quotes <span>'</span> or double quotes <span>"</span>, both are equivalent.
    message1 = "Hello, world!"
    message2 = 'Python is fun!'
    • • When nesting quotes in a string, you can use different types of quotes:
      message = "He said, 'Hello!'"

7. Using Spaces

  • • Add spaces around operators to enhance code readability:
    x = 5 + 3  # Good practice
    y = 7-2    # Not recommended: no spaces around the operator
  • Spaces after commas: When using commas between multiple elements, a space should be added after the comma.
    fruits = ["apple", "banana", "cherry"]

8. Conditional Expressions and Boolean Value Comparisons

  • Boolean values: <span>True</span> and <span>False</span> need to be capitalized.
    is_adult = True
    is_child = False

9. Class and Object Definitions

  • • Class definitions use the class keyword, followed by a colon:
    class Person:  # A colon after class definition
        def __init__(self, name, age):  # Constructor also needs a colon
            self.name = name
            self.age = age

🧠 Conclusion:

  • Colons <span>:</span> are markers of Python syntax, appearing in conditional statements, loops, function definitions, etc.;
  • Indentation: Python uses indentation to indicate code blocks, and indentation must be consistent;
  • Comments: Single-line comments use <span>#</span>, while multi-line comments use <span>"""</span> or <span>'''</span>;
  • Spaces: Use spaces appropriately to enhance code readability, especially around operators, commas, etc.

With these basic formatting guidelines in Python programming, remembering these details can make your code cleaner, more readable, and help avoid common errors.

Leave a Comment