a3_2.py

def open_pdb(code):
	import urllib
	return urllib.urlopen("http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=%s" % code)

def average_coord(code):
	f = open_pdb(code)
	sum_x = sum_y = sum_z = 0.0
	num_atoms = 0
	for line in f:
		if not line.startswith("ATOM"):
			continue
		sum_x += float(line[30:38])
		sum_y += float(line[38:46])
		sum_z += float(line[46:54])
		num_atoms += 1
	if num_atoms == 0:
		print "no atoms were found"
	else:
		avg_x = sum_x / num_atoms
		avg_y = sum_y / num_atoms
		avg_z = sum_z / num_atoms
		print "average coordinates of ", num_atoms, "atoms:", avg_x, avg_y, avg_z
	f.close()

average_coord("3FX2")