🐍

Python: Lecture Notes on Recent Features and Mega Projects

Jul 7, 2024

Python: Lecture Notes on Recent Features and Mega Projects

Virtual Environment (venv)

  • Purpose: Isolates dependencies, avoids conflicts between package versions.

  • Setup:

    pip install virtualenv virtualenv env .\env\Scripts\activate.ps1 # or .\env\Scripts\activate for Bash
    • Deactivate: deactivate
  • Freeze Requirements:

    pip freeze > requirements.txt ``
  • Install from Requirements:

    pip install -r requirements.txt

Walrus Operator (:=)

  • Use: Assign values part of expressions.
  • Example: if (n := len(a_list)) > 3: print(f"List is too long ({n} elements, expected <= 3)")

Type Hinting

  • Basic Type Definition: n: int = 5 name: str = "Harry" def sum(a: int, b: int) -> int: return a + b

Advanced Type Hints

  • Using typing module: from typing import List, Tuple, Dict, Union numbers: List[int] = [1, 2, 3] config: Dict[str, Union[str, int]] = {"key": "value", "port": 8080}

Match-Case (Python 3.10+)

  • Replacement for switch statements: def http_status(code): match code: case 200: return "OK" case 404: return "Not Found" case 500: return "Internal Server Error" case _: return "Unknown code"

Merging Dictionaries

  • Python 3.9+: dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} merged = {**dict1, **dict2}
    • This combines both dictionaries.

Context Managers

  • Multiple Context Managers: with open("file1.txt", "r") as file1, open("file2.txt", "r") as file2: data1 = file1.read() data2 = file2.read()

Exception Handling Enhancements

  • Raising Exceptions: raise ValueError("This is a ValueError")
  • Try with Else: try: result = perform_some_action() except SomeException: handle_exception() else: print("Action performed successfully!")
  • Finally Clause: try: file = open('file.txt', 'r') except Exception as e: handle_exception(e) else: read_file(file) finally: file.close()

Enumerate Function

  • Example: for index, item in enumerate(a_list): print(f"Item {item} is at index {index}")

List Comprehensions

  • Example: squares = [i*i for i in range(10)]

Map, Filter, Reduce Functions

  • Map: Applies function to all items in input list
  • Filter: Filters items out of list
  • Reduce: Applies rolling computation
  • Examples: from functools import reduce nums = [1, 2, 3, 4] squares = list(map(lambda x: x * x, nums)) # [1, 4, 9, 16] evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4] sum_nums = reduce(lambda x, y: x + y, nums) # 10

Mega Project 1: Jarvis - Virtual Assistant

  • Goal: Create a virtual assistant that reacts to voice commands.
  • Dependencies:
    • pyaudio, speech_recognition, pittsx3
  • Example Capabilities:
    • Open Web browser: Google, YouTube, etc.
    • Fetch and read news.
    • Interact with OpenAI.
  • Sample Code: import speech_recognition as sr import webbrowser import pyttsx3 import openai recognizer = sr.Recognizer() engine = pyttsx3.init() client = openai.Client(api_key='YOUR_API_KEY') def speak(text): engine.say(text) engine.runAndWait() while True: with sr.Microphone() as source: audio = recognizer.listen(source) try: command = recognizer.recognize_google(audio).lower() if 'jarvis' in command: speak("Yes?") # Further processing here ... except sr.UnknownValueError: speak("Sorry, I did not get that.") except sr.RequestError: speak("Sorry, my speech service is down.")

Mega Project 2: WhatsApp Bot

  • Goal: Create a bot that replies to WhatsApp messages.
  • Dependencies: pyautogui, piperclip, openai
  • Steps:
    • Use pyautogui to interact with the GUI elements of WhatsApp Web.
    • Use OpenAI API for generating responses.
    • Automate text selection, copying, and pasting responses.
  • Sample Code: import pyautogui import piperclip import openai openai.api_key = 'YOUR_API_KEY' def get_chat_history(): pyautogui.click(x=983, y=74) # Location to click pyautogui.dragTo(x=1498, y=326, duration=1.5, button='left') # Drag to select pyautogui.hotkey('ctrl', 'c') return piperclip.paste() while True: chat_history = get_chat_history() response = openai.Completion.create( engine="davinci", prompt=f"The conversation is: {chat_history}\nRespond like an IT support bot:", max_tokens=150 ) pyautogui.click(x=123, y=456) # Click into the Chat piperclip.copy(response.choices[0].text.strip()) pyautogui.hotkey('ctrl', 'v') # Paste the response pyautogui.press('enter') # Send the message