[Tutor] printing without a new line

Alan Gauld alan.gauld at blueyonder.co.uk
Sun Jun 13 14:12:53 EDT 2004

> aside from the fact that a new line is printed at the end of each
> character conversion.

> def convertxt():
>     x = 0
>     while x <= 26:
>         if char in alphabet[x]:
>             print binary[x] + ' '
>         x += 1

Part of the problem is that you have fallen into the trap of mixing
processing and display. This is always a bad idea. Thus if you were
to return a string from the function instead of printing it things
would be easier.

Also the while loop and 'in' test is pretty inefficient, it would
be easier to use a single in test:

def convertxt():
   if char in alphabet:
     return binary[alphabet.index(char)] + ' '

> def convertnum():
>     whichconv = raw_input("""Convert to:
> 1: Binary
> 2: Hexadecimal
> """)

Similarly it would be better to capture the users requirements outside
the function and pass the value in as a parameter.

binaryChoice = ['1','B','b','Binary','binary','bin']
whichconv = raw_input("""Convert to:
 1: Binary
 2: Hexadecimal

if whichconv in binaryChoice: whichconv = 2
else: whichconv = 16

def convertNum(number, base = 2):
   if base == 2:
      if char in number:
         return binary[int(original) - 1]
   elif base = 16
      if char in number:
         return hexadec[int(original) - 1]

Of course it's better still to use the built in convertion functions
but we've already had that debate...

> import time, string
alphabet = string.letters
> binary = ['','01','10','11','100','101','110','111',
........ double eek! ......

And it really would be easier to use a function to do
the binary conversion!

number = string.numbers

> hexadec =

And itoa() for the hex convertions...

> again = True
> while again:
>     original = raw_input("Please enter numbers or text to be
converted. ")
>     for char in original:
>         try:
>             int(original)
>         except TypeError:
             print convertxt(char),
>         except ValueError:
             print convertxt(char),
>         else:
>             if char in number:
                 print convertnum(char),
>     more = raw_input("Would you like to convert more text or numbers
[y/n]? ")
>     if more in 'Yy':
>         pass
>     elif more in 'Nn':
>         again = False
> print "Thank you for using Multivert.  Multivert will now close"

> time.sleep(1.1)
> import sys
> sys.exit()

Since this is the end of the program you don't need to
import sys
sys.exit() the program will do that by itself.
I'm not sure why you have the sleep(1.1) there either?

This does seem to be an extraordinarily complex way of doing a fairly
simple task, is there any reason other than the fun of experimenting
why you don't just use the builtin features of Python such as
format strings and dictionaries?

Alan G.

More information about the Tutor mailing list