code from www.diveintopython.ne