"OIM3640: GitHub settings"
for
while
break
continue
words = 'the cat sat on the mat'.split() print(len(words)) print(len(set(words)))
print
def mystery(s): return len(set(s)) == len(s) print(mystery('hello')) print(mystery('world'))
mystery
freq = {'a': 3, 'b': 1, 'c': 2} result = sorted(freq.items(), key=lambda x: x[1]) print(result)
result
What happens when something goes wrong in your code?
print(name) # NameError 'hello' + 5 # TypeError my_list[99] # IndexError my_dict['missing'] # KeyError open('nope.txt') # FileNotFoundError
Python crashes at the first error. Can we do better?
try
except
try: age = int(input('Your age: ')) print(f'You are {age} years old') except ValueError: print('That is not a valid number!')
scores = {'Alice': 95, 'Bob': 87} try: name = input('Student name: ') print(f'{name}: {scores[name]}') except KeyError: print(f'{name} not found')
Always catch specific exceptions, not bare except:.
except:
Next up: we'll use this with APIs!
Your Python code --> HTTP request --> API server <-- JSON response <--
Examples: current Bitcoin price, weather data, people in space...
JSON looks just like Python dicts and lists:
{ "name": "Boston", "temp": 72.5, "tags": ["sunny", "warm"], "wind": {"speed": 8, "dir": "NW"} }
response.json() converts JSON to a Python dict. That's it!
response.json()
Install the requests library:
requests
pip install requests
Your first API call - just 3 lines:
import requests response = requests.get('https://oim.108122.xyz/words/random') print(response.json()) # a random word!
Try it now!
response = requests.get('https://oim.108122.xyz/mass') data = response.json() print(data['name']) # 'Massachusetts' print(data['governor']) # 'Maura Healey' for town in data['data'][:5]: print(f"{town['name']}: pop {town['population']:,}")
Nested JSON: dicts inside lists inside dicts.
try: response = requests.get('https://oim.108122.xyz/mass') data = response.json() print(data['name']) except requests.exceptions.ConnectionError: print('Cannot connect to the API') except KeyError as e: print(f'Missing key: {e}')
APIs can fail: network down, server errors, missing data.
# GET: read/fetch data requests.get('https://oim.108122.xyz/words/random') # POST: send/submit data requests.post('https://oim.108122.xyz/echo', json={'name': 'Alice', 'course': 'OIM3640'})
Visit oim.108122.xyz/echo/view in your browser. What happens? Why?
Open oim.108122.xyz/live on the projector.
import requests response = requests.get( 'https://oim.108122.xyz/words/random', headers={'X-Token': 'alicealice'}, # your first name x2 ) print(response.json())
Your name appears on the dashboard! (No token → "Anonymous")
API docs: oim.108122.xyz/docs
url = 'http://api.open-notify.org/astros.json' data = requests.get(url).json() print(f"{data['number']} people in space right now!") for p in data['people']: print(f" {p['name']} on {p['craft']}")
Also try: CoinDesk Bitcoin API - paste in browser!
Some APIs require an API key for access.
API_KEY = 'abc123...' # Don't hardcode this! url = (f'https://api.openweathermap.org/data/2.5/weather' f'?q=Boston&appid={API_KEY}&units=imperial') data = requests.get(url).json() print(f"Boston: {data['main']['temp']}°F")
How do we protect the key?
import os from dotenv import load_dotenv load_dotenv() API_KEY = os.getenv('OPENWEATHER_API_KEY')
pip install python-dotenv
.env
OPENWEATHER_API_KEY=abc123...
.gitignore
os.getenv()
Same pattern, different API:
from openai import OpenAI client = OpenAI() # reads OPENAI_API_KEY from .env response = client.chat.completions.create( model='gpt-4o-mini', messages=[{'role': 'user', 'content': 'Hello!'}] ) print(response.choices[0].message.content)
OpenAI Quickstart
Option A: Weather for your hometown
Option B: Explore Massachusetts towns
oim.108122.xyz/mass
founded
logs/wk10.md
Next session: File I/O (reading, writing, CSV, JSON)
global styles