[Tutor] Declare empty string variable?

Bob Gailer ramrom@earthling.net
Mon Dec 30 12:54:01 2002


--=======22533F2A=======
Content-Type: text/plain; x-avg-checked=avg-ok-DE17EEF; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

### Decimal to Binary Conversion
 > deci=input("Decimal? --> ")
 > dual= <--- declaration
 > ...
 > while deci>0:
 >     dual_tmp=deci%2
 >     dual=dual_tmp, dual <--- change dual here

Observations:
  this program does not reassign to deci; therefore it is an endless loop.
  while deci>0: can just be while deci:

Try this:
dual = ''
deci = input("Decimal? --> ")
while deci:
   deci,b = divmod(deci,2)
   dual=str(b)+dual
print dual

If you plan to use this a lot (where performance might be impacted) an 
alternative is:
# dictionary uses hex digits as keys values are corresponding binary strings
dict = {'0': '0000', '1': '0001', ... '9': '1001', 'A': '1010', ... 'F': 
'1111'} # fill in the ellipses!
hex = '%X' % deci # convert decimal to string of hex characters
dual = ''.join([dict[x] for x in hex]) # translate and combine

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625

--=======22533F2A=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-DE17EEF
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002

--=======22533F2A=======--