Python for AI: A Crash Course

Nov 16 2024 · Python 3.12, JupyterLab 4.2.4

Lesson 02: Python Syntax & Best Practices

Writing Python Code Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Instructions

Python’s design philosophy emphasizes simplicity, readability, and ease of use, making it an accessible language for both beginners and experienced developers. The Python community has adopted this philosophy for their code, and as a Python programmer, you’re encouraged to do the same. In this section, you’ll learn general guidelines and best practices to follow when writing your own Python programs by improving a couple of small Python apps.

The Zen Of Python And Pythonic Code

There’s an “Easter egg” built into Python. To see it, Open the checklist-starter.ipynb notebook. Enter the following into a new code cell and run it:

# Run me!
import this

PEP 8

The Zen of Python is a good read, but if you want more concrete guidance on writing Python code, you should consult the document known throughout the Python community as PEP 8.

Refactoring An App To Make It More Pythonic

It’s time to take a working app written in Python and refactor its code. Refactoring better utilizes Python’s features and follows the guidelines and practices of the Python community.

Using Brackets To Make Long Lines Readable

Find the code cell stating with the comment # Initial checklist. It contains a line that defines checklist, a list of ChecklistItem instances representing the contents of the checklist.

# Initial checklist
checklist = [
  ChecklistItem("Clean the living room"),
  ChecklistItem("Walk the dog", True, "high"),
  ChecklistItem("Buy groceries"),
  ChecklistItem("Make dinner", priority="high")
]

Putting A Comma After The Last Item In A List, Tuple, Set, Or Dictionary Literal

Add one more item to the end of checklist:

  ChecklistItem("Fix toaster")

Using The __repr__() Method When Defining Classes

Confirm that the changes you made work by entering checklist into a new code cell and running it. If you get an error make sure you have run all the previous cells before running the newly created one. This will display the list’s contents, with each Checklistitem instance in the list represented by the output of the __repr__() method. Remember, __repr__() returns the developer-facing string representation of an instance.

Using Python’s Ternary Operator

Look at ChecklistItem’s __str__() method, which returns the user-facing string representation of an instance. It sets a variable named checkbox to a checked box emoji if the checklist item it represents is checked or a gray box emoji representing an unchecked box if it’s unchecked.

  def __str__(self):
    """Return a user-friendly string representation of the item."""
    return f"{"✅" if self.checked else "⬜️"} {self.name} {self.priority_emoji()}({self.priority})"

Using Truthy and Falsy Values To Make Code Concise

Go to the code cell where the display_checklist() function is defined. The function works, but it could be improved.

# Show the user the checklist
def display_checklist(checklist):
  """Show the user the checklist."""
  if checklist:
    item_number = 1
    for item in checklist:
      print(f"{item_number}: {item}")
      item_number += 1
  else:
    print("The checklist is empty.")

Using enumerate() When Iterating To Get Both Index And Item

display_checklist() still has room for improvement. If checklist isn’t empty, the current code uses a for loop to iterate through the list items, and it also sets up the index variable to store the number of the item currently being printed. The index variable is incremented at the end of each iteration.

# Show the user the checklist
def display_checklist(checklist):
  """Show the user the checklist."""
  if checklist:
    for index, item in enumerate(checklist, start=1):
      print(f"{index}: {item}")
  else:
    print("The checklist is empty.")

Maybe You Need An in, Not An or

Find the code cell where the add_item_to_checklist() function is defined. Note that after it gets the user’s input about the item’s priority, it performs three if comparisons joined by or operators to see if the user entered low, medium, or high. This would get unwieldy if there were more valid options.

def add_item_to_checklist(checklist):
  """
  Get an item name and priority from the user
  and add it to the checklist.
  """
  while True:
    name = input("What's the item's name?").strip()
    if name:
      break
    print("Please enter a name for the item.")
  while True:
    priority = input("What's its priority (low, medium, or high)?").strip().lower()
    if priority in ["low", "medium", "high"]:
      break
    else:
      print("Please enter 'low', 'medium', or 'high'.")
  new_item = ChecklistItem(name, False, priority)
  checklist.append(new_item)

You Can Chain Comparisons

Go to the code cell containing the edit_item_in_checklist() function. After the line that asks the user which item they want to edit, there’s an if that compares the value of index to confirm that it’s between 0 as a lower bound and len(checklist) as an upper bound. Whenever you see this kind of comparison, chain them.

def edit_item_in_checklist(checklist):
  if not checklist:
    print("There are no items in the checklist. There's nothing to edit.")
    return

  print("Here are the items:")
  display_checklist(checklist)
  index = int(input("Which item do you want to edit?")) - 1
  if 0 <= index < len(checklist):
    while True:
      name = input("What's the item's name?").strip()
      if name:
        break
      print("Please enter a name for the item.")
    while True:
      priority = input("What do you want to change the priority to (low, medium, or high)?")
      if priority in ["low", "medium", "high"]:
        break
      print("Please enter 'low', 'medium', or 'high'.")
    checklist[index].name = name
    checklist[index].priority = priority

Using f-strings Instead Of String Concatenation

Find the code cell where the delete_item_from_checklist() function is defined. Here’s the line in that function that builds the string asking the user if they’re sure they want to delete an item:

question = "Are you sure you want to delete " + checklist[index].name + "?"
def delete_item_from_checklist(checklist):
  """
  Ask the user to select a checklist item,
  then delete it if they're sure.
  """
  if not checklist:
    print("There are no items in the checklist. There's nothing to edit.")
    return

  print("Here are the items:")
  display_checklist(checklist)
  index = int(input("Which item do you want to delete?")) - 1
  if 0 <= index < len(checklist):
    question = f"Are you sure you want to delete {checklist[index].name}?"
    answer = input(question).strip().lower()
    if answer.lower() in ["y", "yes", "ok", "okey dokey"]:
      deleted_item = checklist.pop(index)
      print(f"Deleted {deleted_item.name}.")

Dictionaries Can Be Decision Makers

Run the cells containing check_item() and uncheck_item(). Scroll past them and find the cell containing main(), the app’s main function.

  # Act on the user’s selection
  ACTIONS = {
    1: display_checklist,
    2: check_item,
    3: uncheck_item,
    4: add_item_to_checklist,
    5: edit_item_in_checklist,
    6: delete_item_from_checklist,
  }
  print("\n")
  if 1 <= choice <= 6:
      ACTIONS[choice](checklist)
  elif choice == 7:
    print("Checklist main() finished.")
    break
  else:
    print("Please enter a valid choice (1 - 7).")
  print("\n")
See forum comments
Cinema mode Download course materials from Github
Previous: Classes & Objects Next: Python Syntax & Best Practices - Conclusion