Python Flashcards

1
Q

Syntax: open a file for reading [#to write in it]

A

f = open(“foo.txt”, “r”) # f = open(“bar.txt”, “w”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Syntax: read a file

A

data = f.read #where f is the result of: open(“foo.txt”, “r”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Syntax: write to a file

A

g.write(“some text\n”) #where g is a result of open(“bar.txt”, “w”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Syntax: reading a file one line at a time

A

f = open(“foo.txt”,”r”)
for line in f:
#process line
f.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Syntax: reading from the web

A

import urllib

u = urllib.urlopen("www.google.com")
data = u.read()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Syntax: parse an xml doc

A

from xml.etree.ElementTree import parse

doc = parse(‘rt22.xml’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Syntax: iterate over an element in a parsed xml doc

A
for element in doc.findall('element'):
    #code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Syntax: extract data from a parsed xml doc

A

d = element.findtext(‘d’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Syntax: show a page in a browser

A

import webbrowser

webbrowser.open(‘http://…’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Syntax: chained comparison

A
if x < y >= z:
#same as: if x < y and y >= z: 
#but! y only evaluated once, z not if x <y false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Syntax: preferred way to open a file! (to ensure it is closed)

A
with open('name', 'mode') as f:
    read_data = f.read()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Syntax: start the development server

A

python manage.py runserver

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Syntax: awesome list comprehension

A

output = ‘, ‘.join([p.question for p in latest_poll_list])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly