Skip to content

Commit 334e97a

Browse files
committed
Add Python programming tips I've collected.
1 parent 94b8e7b commit 334e97a

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

python-tips.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Python Tips
2+
3+
## List, set, and dictionary comprehensions
4+
```python
5+
my_list = []
6+
for i in range(4):
7+
my_list.append(i)
8+
9+
my_list = [i for i in range(4)]
10+
11+
my_dict = []
12+
for i in range(4):
13+
my_dict.append(i)
14+
15+
names = ['Alice', 'Bob', 'Claire']
16+
aliases = ['Angel', 'Bobo', 'Clack']
17+
my_dict = {name: alias for name, alias in zip(names, aliases)}
18+
19+
my_set = set([i for i in range(4)])
20+
```
21+
22+
## Generators
23+
```python
24+
for i in range(4):
25+
yield i
26+
27+
my_generator = (i for i in range(4))
28+
```
29+
30+
## Iterators
31+
Iterators are objects with __iter__() and __next__() methods.
32+
33+
The itertools module helps you efficiently loop through iterables.
34+
35+
```python
36+
import itertools
37+
38+
counter = itertools.count()
39+
```
40+
41+
## Web Scraping
42+
Beautiful Soup makes it easy to parse HTML.
43+
44+
```bash
45+
pip install beautifulsoup4
46+
pip install lxml
47+
pip install html5lib
48+
pip install requests
49+
```
50+
```python
51+
from bs4 import BeautifulSoup
52+
import requests
53+
54+
with open('example.html') as html_file:
55+
soup = BeautifulSoup(html_file, 'lxml')
56+
57+
print(soup.prettify())
58+
59+
match = soup.title
60+
print(match)
61+
```

0 commit comments

Comments
 (0)