|
|
Python for Everybody 을 읽었다. 변수이름은 맘대로 정해도 된다. 하지만 예약어는 이미 시스템이 사용하고 있기에 사용하면 에러가 발생한다. 함수도 마찬가지다. 내장함수가 아닌 모듈의 경우는 사용가능하지만 import된 이후는 내장화되기에 사용할 수없다. 많이 임포트하는 모듈로 수학함수가 있다. 모듈중 하나의 함수에 접근하려면 모듈.함수로 사용하면 된다. 예를 들어 데시벨을 계산하려면 비율=신호/잡음 데시벨=10*math.log10(비율)로 코딩하여 수학모듈의 로그함수에 접근하여 구할 수있다. 57
함수를 만들어 사용하면 내장함수나 임포트한 함수를 사용하는 것과 같이 반복코딩을 줄일 수있기에 코딩이 짧아지고 이해나 디버깅이 쉬워진다. 또한 탭과 공백은 보이지 않기에 디버깅이 어려우므로 공백만 사용하는 것이 추천된다. 64 코딩이 커지면 디버깅도 어려워진다. 디버깅시간을 줄이는 방법은 중간값의 확인이다. 100줄의 디버깅을 처음부터 하면 100번에 필요한 시간이 반으로 줄이면 이론적으로 6번으로 줄어든다. 76 리스트는 변경가능하고 음수인 경우는 리스트 끝에서의 순서다. 즉 0은 리스트의 시작이고 -1은 끝을 의미한다. 정수, 실수, 문자, 리스트가 리스트에 포함될 수있다. 103
리스트를 처리하는 메소드가 제공된다. 메소드는 extend, sort, pop, del, remove 등이 있다.
>>> t = [a, b, c]
>>> t.append(d)
>>> print(t)
[a, b, c, d] 106
해시테이블(Hash Table)은 데이터를 키(key)와 값(value)의 쌍으로 저장하고, 키를 해시 함수(hash function)에 넣어 배열의 인덱스를 계산해 매우 빠르게 데이터를 조회·삽입·삭제할 수 있는 자료구조다.
# 해시테이블이 중요한 이유
* 평균 시간복잡도 O(1) → 검색(Search), 삽입(Insert), 삭제(Delete)이 매우 빠름
* 많은 프로그래밍 언어의 기본 자료구조로 사용: Python의 `dict`, Java의 `HashMap`, JavaScript의 `{}`, Go의 `map`
# 해시테이블의 작동 원리
1. 키(key)가 들어오면
2. 해시 함수(hash function)가 이 키를 정수값으로 변환
3. 그 값을 기반으로 배열 인덱스를 계산
4. 해당 위치에 값을 저장
```
키 → 해시함수 → 인덱스 → 값 저장/조회
```
# 해시 충돌(Collision); 서로 다른 키가 같은 인덱스를 갖게 되는 현상 ➜ 완전히 피할 수는 없음
대처법:
1. 체이닝(Chaining) – 같은 인덱스에 연결 리스트로 여러 값 저장
2. 오픈 어드레싱(Open Addressing) – 비어 있는 다른 버킷을 찾아 저장; * Linear probing * Quadratic probing * Double hashing 등
# 시간복잡도
| 연산 | 평균 | 최악 |
| 검색 | O(1) | O(n) |
| 삽입 | O(1) | O(n) |
| 삭제 | O(1) | O(n) |
최악은 충돌이 모두 한 곳에 몰릴 때 발생하지만, 좋은 해시 함수 + 적절한 버킷 크기로 평균은 거의 O(1) 유지.
# 간단한 예 (파이썬)
```python
table = {}
table["apple"] = 3
table["banana"] = 5
print(table["apple"]) # 3
``` 122
정규표현식(Regular Expression, RegEx)은 문자열에서 특정 패턴을 찾거나 검사하거나 치환하기 위해 사용하는 표현식이다. 검색, 데이터 검증, 텍스트 변환 등에 매우 강력하게 활용된다.
# 정규표현식 기본 개념
1) 문자 매칭
| . | 아무 문자 1개 |
| \d | 숫자(0–9) |
| \w | 문자+숫자+밑줄 |
| \s | 공백 문자 |
| \D, \W, \S | 각각의 반대 의미 |
2) 수량자(반복)
| * | 0회 이상 반복 |
| + | 1회 이상 반복 |
| ? | 0 또는 1 |
| {n} | 정확히 n회 |
| {n,} | n회 이상 |
| {n,m} | n~m회 |
3) 문자 클래스
| [abc] | a 또는 b 또는 c |
| [a-z] | a~z 범위 |
| [^0-9] | 숫자가 아닌 문자 |
4) 경계(Boundary)
| ^ | 문자열 시작 |
| $ | 문자열 끝 |
| \b | 단어 경계 |
| \B | 단어 경계 아님 |
5) 그룹핑 / 캡처
| (abc) | 그룹화 | |
| (?:abc) | 비캡처 그룹 | |
| (a | b) | a 또는 b |
# 자주 쓰는 정규식 예시
✔ 이메일 검사; ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
✔ 휴대폰 번호(010-xxxx-xxxx); ^010-\d{4}-\d{4}$
✔ 숫자만; ^\d+$
✔ 비밀번호(8~20자, 문자/숫자/특수문자 포함); ^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*]).{8,20}$
# 파이썬 예제
```python
import re
pattern = r"\d+"
text = "My number is 12345"
result = re.findall(pattern, text)
print(result) # ['12345']
``` 143
객체지향 프로그래밍(Object-Oriented Programming, OOP)은 프로그램을 객체(object)라는 독립적인 단위들의 상호작용으로 구성하는 프로그래밍 패러다임이다. 현실 세계의 개념을 프로그램에 자연스럽게 표현할 수 있어 재사용성, 확장성, 유지보수성이 뛰어나다.
# OOP의 핵심 개념 (4대 특징)
*추상화(Abstraction); 복잡한 시스템에서 핵심적인 특징만 남기고 불필요한 세부 정보는 숨기는 것→ “핵심만 간단히 표현하기”
예)
```python
class Animal:
def sound(self):
pass
```
*캡슐화(Encapsulation); 데이터(속성)와 기능(메서드)을 한 객체 안에 묶고, 외부 접근은 제한→ “중요한 데이터는 숨기고, 필요한 기능만 공개”
예)
```python
class BankAccount:
def __init__(self):
self.__balance = 0 # private
def deposit(self, amount):
self.__balance += amount
```
*상속(Inheritance); 기존 클래스를 기반으로 새로운 클래스를 만드는 것→ “부모의 기능을 자식이 물려받아 재사용”
예)
```python
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Woof!")
```
*다형성(Polymorphism); 같은 메서드 이름이지만 객체 종류에 따라 다르게 동작→ “같은 요청을 해도 각 객체가 자신만의 방식으로 반응”
예)
```python
animals = [Dog(), Cat()]
for a in animals:
a.sound() # 각자 다른 소리
```
# 객체 = 속성 + 메서드
예) “자동차”라는 객체
* 속성(Attributes): 색상, 모델, 속도
* 메서드(Methods): 가속, 정지, 방향 전환
# OOP가 왜 좋은가?
| 재사용성 | 상속, 모듈화를 통해 반복 작업을 줄임 |
| 유지보수성 | 결합도가 낮아 문제가 생겨도 수정이 쉬움 |
| 확장성 | 새 기능 추가가 자연스럽고 구조적 |
| 현실 세계 모델링 용이 | 객체 중심 설계로 이해하기 쉬움 |
# 간단한 예 (Python)
```python
class Car:
def __init__(self, brand, speed=0):
self.brand = brand
self.speed = speed
def accelerate(self):
self.speed += 10
car = Car("Tesla")
car.accelerate()
print(car.speed) # 10
``` 179
stuff = list() # 리스트유형객체생성
stuff.append(python) # 어팬드메서드호출
stuff.append(chuck)
stuff.sort() # 소트메서드호출
print (stuff[0]) # 위치0에서 항목검색
print (stuff.__getitem__(0)) # 겟아이템메서드호출
print (list.__getitem__(stuff,0)) # 목록에서 0번째항목 검색 180
데이터베이스(Database)는 데이터를 체계적으로 저장하고 관리하여 조회, 수정, 삭제, 추가 작업을 효율적으로 할 수 있게 만든 시스템이다. 많은 프로그램·웹사이트·앱이 데이터를 다루기 때문에 필수 기술이다.
1. 데이터베이스란?
* 데이터를 모아둔 곳(저장소)
* 데이터를 빠르고 안정적으로 검색·관리하는 것이 목적
* 여러 사용자가 동시에 접근해도 일관성(Consistency)과 정확성을 유지
2. 데이터베이스의 종류
1) 관계형 데이터베이스(RDBMS); 테이블(표) 형태로 데이터를 저장→ SQL 사용
예: MySQL, PostgreSQL, Oracle, MariaDB, SQL Server
특징; * 정규화로 데이터 중복 최소화 * 스키마(자료형·구조)가 명확함 * 강력한 트랜잭션 지원
2) 비관계형 데이터베이스(NoSQL); 테이블 구조가 아닌 유연한 방식→ JSON, Key-Value, Document 등
예: MongoDB, Redis, Cassandra, DynamoDB
특징; * 대용량·고속 처리에 강함 * 스키마가 유연함 * 수평 확장(Scaling)이 쉬움
3. SQL 기본 개념
✔ CRUD
| 동작 | SQL |
| Create | `INSERT` |
| Read | `SELECT` |
| Update | `UPDATE` |
| Delete | `DELETE` |
예)
```sql
SELECT name, age FROM users WHERE age > 20;
```
4. 트랜잭션(Transaction); 데이터베이스에서 하나의 논리적 작업 단위→ ACID 특징을 만족해야 함
| Atomicity | 원자성: 전부 실행 or 전부 취소 |
| Consistency | 일관성: 규칙을 깨지 않음 |
| Isolation | 격리성: 다른 트랜잭션과 독립 |
| Durability | 지속성: 완료된 내용은 유지 |
5. 데이터베이스 설계의 핵심
* 정규화(Normalization) → 중복 제거, 구조화
* ERD(Entity Relationship Diagram) → 테이블 관계 설계
* 인덱스(Index) → 빠른 검색 수행
* 조인(Join) → 여러 테이블을 연결해 조회; * INNER JOIN * LEFT/RIGHT JOIN * FULL JOIN
6. 예시: 간단한 테이블 생성
```sql
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(100) UNIQUE
);
```
7. 어디에 쓰일까?; 실제 거의 모든 서비스의 핵심 기반이 DB
* 회원가입/로그인
* 게시글 저장
* 장바구니
* 결제 시스템
* 게임 유저 정보
* IoT 센서 데이터 저장 193
SQLite용 데이터베이스 브라우저는 다음에서 무료로 제공된다. https://sqlitebrowser.org/이를 통해 쉽게 테이블을 만들고 데이터를 삽입하거나 편집하고 데이터베이스의 데이터에 대해 간단한 퀴리를 실행할 수있다. 194
데이터 시각화(Data Visualization)는 데이터를 차트, 그래프, 이미지 등 시각 형태로 표현하여 데이터의 의미, 패턴, 트렌드를 쉽게 이해하도록 만드는 기술이다. 데이터 분석·AI·비즈니스·과학 등 거의 모든 분야에서 필수다.
1. 데이터 시각화가 중요한 이유
* 복잡한 데이터를 빠르게 이해할 수 있음
* 패턴·이상치·변화를 직관적으로 파악
* 의사결정을 위한 설득력 있는 스토리텔링 가능
* 문제점을 신속히 발견
2. 자주 사용하는 시각화 종류
✔ 범주형 데이터(Category) * 막대그래프(Bar Chart) * 파이 차트(Pie Chart) * 트리맵(Treemap)
✔ 연속형(수치) 데이터(Numerical) * 선형 그래프(Line Plot) * 히스토그램(Histogram) * 상자 그래프(Box Plot)
✔ 관계(Relationship) * 산점도(Scatter Plot) * 버블 차트(Bubble Chart)
✔ 시계열(Time Series) * 라인 차트(Line Chart) * 에리어 차트(Area Chart)
✔ 고급 시각화 * 히트맵(Heatmap) * 네트워크 그래프(Network Graph) * 지도 시각화(Geospatial) * 대시보드(Tableau, Power BI, Dash, Streamlit)
3. 데이터 시각화 도구
✔ 프로그래밍 기반
* Python: Matplotlib, Seaborn, Plotly, Bokeh
* R: ggplot2, Shiny
* xxJavaScript: D3.js, Chart.js
✔ UI 기반(코드 없이)
* Tableau
* Power BI
* Google Data Studio
* Looker Studio
4. Python 시각화 예제
✔ Matplotlib
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 30]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
```
✔ Seaborn (더 예쁜 기본 스타일)
```python
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip")
plt.show()
```
5. 좋은 데이터 시각화의 원칙
* 목적에 맞는 차트 선택
* 불필요한 장식 최소화(차트 잉크 최소화)
* 라벨·단위 명확히 표기
* 색상 남용 X
* 데이터 왜곡 금지
* 스토리 전달이 명확해야 함
6. 무엇을 도와드릴까요?
* 특정 데이터를 시각화해드리기
* 파이썬 코드 작성
* 어떤 상황에서 어떤 차트가 좋은지 추천
* 대시보드 설계
* 시각화 예제 자료 만들기 229
/241=229+12 229=217+12 217=205+12 193=181+12 179=167+12 171=159+12 157=145+12 143=131+12 131=119+12 121=109+12 103=91+12 91=79+12 79=67+12 69=57+12 55=43+12 43=31+12 31=19+12 17=5+12
https://it-ebooks.dev/books/programming/python-for-everybody
1 Whyshouldyoulearntowriteprograms? 1 1.1 Creativityandmotivation . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 Computerhardwarearchitecture . . . . . . . . . . . . . . . . . . . 3 1.3 Understandingprogramming . . . . . . . . . . . . . . . . . . . . . 4 1.4 Wordsandsentences . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.5 ConversingwithPython. . . . . . . . . . . . . . . . . . . . . . . . 6 1.6 Terminology: Interpreterandcompiler . . . . . . . . . . . . . . . . 8 1.7 Writingaprogram . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.8 What isaprogram? . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.9 Thebuildingblocksofprograms . . . . . . . . . . . . . . . . . . . 11 1.10 Whatcouldpossiblygowrong? . . . . . . . . . . . . . . . . . . . . 12 1.11 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.12 Thelearningjourney. . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.13 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2 Variables,expressions,andstatements 19 2.1 Valuesandtypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3 Variablenamesandkeywords . . . . . . . . . . . . . . . . . . . . . 21 2.4 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.5 Operatorsandoperands . . . . . . . . . . . . . . . . . . . . . . . . 22 2.6 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.7 Orderofoperations . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.8 Modulusoperator . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.9 Stringoperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.10 Askingtheuserforinput . . . . . . . . . . . . . . . . . . . . . . . 25 2.11 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 2.12 Choosingmnemonicvariablenames . . . . . . . . . . . . . . . . . 27 2.13 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.14 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3 Conditionalexecution 31 3.1 Booleanexpressions . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.2 Logicaloperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.3 Conditionalexecution . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.4 Alternativeexecution . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.5 Chainedconditionals. . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.6 Nestedconditionals . . . . . . . . . . . . . . . . . . . . . . . . . . 35 3.7 Catchingexceptionsusingtryandexcept . . . . . . . . . . . . . . 36 3.8 Short-circuitevaluationof logicalexpressions . . . . . . . . . . . . 38
3.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.10 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4 Functions 43 4.1 Functioncalls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.2 Built-infunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3 Typeconversionfunctions . . . . . . . . . . . . . . . . . . . . . . . 44 4.4 Mathfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.5 Randomnumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 4.6 Addingnewfunctions . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.7 Definitionsanduses . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.8 Flowofexecution . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.9 Parametersandarguments . . . . . . . . . . . . . . . . . . . . . . 49 4.10 Fruitful functionsandvoidfunctions . . . . . . . . . . . . . . . . . 51 4.11 Whyfunctions?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.13 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5 Iteration 57 5.1 Updatingvariables . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 5.2 Thewhilestatement . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.3 Infiniteloops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.4 Finishingiterationswithcontinue. . . . . . . . . . . . . . . . . . 59 5.5 Definiteloopsusingfor . . . . . . . . . . . . . . . . . . . . . . . . 60 5.6 Looppatterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 5.6.1 Countingandsummingloops . . . . . . . . . . . . . . . . . 61 5.6.2 Maximumandminimumloops . . . . . . . . . . . . . . . . 62
5.7 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.8 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6 Strings 67 6.1 Astringisasequence . . . . . . . . . . . . . . . . . . . . . . . . . 67 6.2 Gettingthelengthofastringusinglen . . . . . . . . . . . . . . . 68
6.3 Traversal throughastringwithaloop . . . . . . . . . . . . . . . . 68 6.4 Stringslices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 6.5 Stringsareimmutable . . . . . . . . . . . . . . . . . . . . . . . . . 70 6.6 Loopingandcounting . . . . . . . . . . . . . . . . . . . . . . . . . 70 6.7 Theinoperator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 6.8 Stringcomparison . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.9 Stringmethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 6.10 Parsingstrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 6.11 FormattedStringLiterals . . . . . . . . . . . . . . . . . . . . . . . 74 6.12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 6.13 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 6.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7 Files 79 7.1 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 7.2 Openingfiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.3 Textfilesandlines . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 7.4 Readingfiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 7.5 Searchingthroughafile . . . . . . . . . . . . . . . . . . . . . . . . 83 7.6 Lettingtheuserchoosethefilename. . . . . . . . . . . . . . . . . 85 7.7 Usingtry, except,andopen . . . . . . . . . . . . . . . . . . . . 86 7.8 Writingfiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 7.10 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 7.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8 Lists 91 8.1 Alist isasequence. . . . . . . . . . . . . . . . . . . . . . . . . . . 91 8.2 Listsaremutable. . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.3 Traversingalist . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 8.4 Listoperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 8.5 Listslices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 8.6 Listmethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 8.7 Deletingelements . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 8.8 Listsandfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.9 Listsandstrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 8.10 Parsinglines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 8.11 Objectsandvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 8.12 Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 8.13 Listarguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 8.14 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.15 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 8.16 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9 Dictionaries 109 9.1 Dictionaryasasetofcounters . . . . . . . . . . . . . . . . . . . . 111 9.2 Dictionariesandfiles. . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.3 Loopinganddictionaries . . . . . . . . . . . . . . . . . . . . . . . 114 9.4 Advancedtextparsing . . . . . . . . . . . . . . . . . . . . . . . . . 115 9.5 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 9.6 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10Tuples 119 10.1 Tuplesareimmutable . . . . . . . . . . . . . . . . . . . . . . . . . 119 10.2 Comparingtuples . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
10.3 Tupleassignment. . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 10.4 Dictionariesandtuples . . . . . . . . . . . . . . . . . . . . . . . . 123 10.5 Multipleassignmentwithdictionaries . . . . . . . . . . . . . . . . 124
10.6 Themostcommonwords . . . . . . . . . . . . . . . . . . . . . . . 125 10.7 Usingtuplesaskeysindictionaries. . . . . . . . . . . . . . . . . . 126 10.8 Sequences: strings, lists,andtuples-OhMy! . . . . . . . . . . . . 126 10.9 Listcomprehension . . . . . . . . . . . . . . . . . . . . . . . . . . 127 10.10 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 10.11 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 10.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
11Regularexpressions 131 11.1 Charactermatchinginregularexpressions. . . . . . . . . . . . . . 132 11.2 Extractingdatausingregularexpressions . . . . . . . . . . . . . . 133 11.3 Combiningsearchingandextracting . . . . . . . . . . . . . . . . . 136 11.4 Escapecharacter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 11.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 11.6 BonussectionforUnix/Linuxusers. . . . . . . . . . . . . . . . . 141 11.7 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 11.8 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 11.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
12Networkedprograms 145 12.1 HypertextTransferProtocol-HTTP . . . . . . . . . . . . . . . . 145 12.2 Theworld’ssimplestwebbrowser . . . . . . . . . . . . . . . . . . 146 12.3 RetrievinganimageoverHTTP . . . . . . . . . . . . . . . . . . . 148 12.4 Retrievingwebpageswithurllib . . . . . . . . . . . . . . . . . . 150 12.5 Readingbinaryfilesusingurllib . . . . . . . . . . . . . . . . . . 151 12.6 ParsingHTMLandscrapingtheweb . . . . . . . . . . . . . . . . 152 12.7 ParsingHTMLusingregularexpressions . . . . . . . . . . . . . . 152 12.8 ParsingHTMLusingBeautifulSoup . . . . . . . . . . . . . . . . . 154 12.9 BonussectionforUnix/Linuxusers. . . . . . . . . . . . . . . . . 157 12.10 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 12.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
13UsingWebServices 159 13.1 eXtensibleMarkupLanguage-XML. . . . . . . . . . . . . . . . . 159 13.2 ParsingXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 13.3 Loopingthroughnodes . . . . . . . . . . . . . . . . . . . . . . . . 161 13.4 JavaScriptObjectNotation-JSON . . . . . . . . . . . . . . . . . 162 13.5 ParsingJSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 13.6 ApplicationProgrammingInterfaces . . . . . . . . . . . . . . . . . 164 13.7 SecurityandAPIusage . . . . . . . . . . . . . . . . . . . . . . . . 165 13.8 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
14Object-orientedprogramming 167 14.1 Managinglargerprograms. . . . . . . . . . . . . . . . . . . . . . . 167 14.2 Gettingstarted. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 14.3 Usingobjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 14.4 Startingwithprograms . . . . . . . . . . . . . . . . . . . . . . . . 169 14.5 Subdividingaproblem. . . . . . . . . . . . . . . . . . . . . . . . . 171 14.6 OurfirstPythonobject . . . . . . . . . . . . . . . . . . . . . . . . 171 14.7 Classesastypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 14.8 Objectlifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 14.9 Multipleinstances . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 14.10 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 14.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 14.12 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
15UsingDatabasesandSQL 181 15.1 What isadatabase? . . . . . . . . . . . . . . . . . . . . . . . . . . 181 15.2 Databaseconcepts . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 15.3 DatabaseBrowserforSQLite . . . . . . . . . . . . . . . . . . . . . 182 15.4 Creatingadatabasetable . . . . . . . . . . . . . . . . . . . . . . . 182 15.5 StructuredQueryLanguagesummary . . . . . . . . . . . . . . . . 185 15.6 Multipletablesandbasicdatamodeling . . . . . . . . . . . . . . . 187 15.7 Datamodeldiagrams . . . . . . . . . . . . . . . . . . . . . . . . . 189 15.8 Automaticallycreatingprimarykeys . . . . . . . . . . . . . . . . . 190 15.9 Logicalkeysforfast lookup . . . . . . . . . . . . . . . . . . . . . . 191 15.10 Addingconstraintstothedatabase. . . . . . . . . . . . . . . . . . 192 15.11 Samplemulti-tableapplication . . . . . . . . . . . . . . . . . . . . 193 15.12 Manytomanyrelationshipsindatabases . . . . . . . . . . . . . . 196 15.13 Modelingdataatthemany-to-manyconnection . . . . . . . . . . 200 15.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 15.15 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 15.16 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
16Visualizingdata 205 16.1 BuildingaOpenStreetMapfromgeocodeddata. . . . . . . . . . . 205 16.2 Visualizingnetworksandinterconnections . . . . . . . . . . . . . . 207 16.3 Visualizingmaildata . . . . . . . . . . . . . . . . . . . . . . . . . 210
AContributions 217 A.1 Translations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 A.2 ContributorListforPythonforEverybody . . . . . . . . . . . . . 217
A.3 ContributorListforPythonforInformatics . . . . . . . . . . . . . 218 A.4 Prefacefor“ThinkPython” . . . . . . . . . . . . . . . . . . . . . . 218 A.4.1 Thestrangehistoryof“ThinkPython” . . . . . . . . . . . 218 A.4.2 Acknowledgementsfor“ThinkPython” . . . . . . . . . . . 219 A.5 ContributorListfor“ThinkPython”. . . . . . . . . . . . . . . . . 220
BCopyrightDetail 221
