[Tutor] printing without a new line
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:
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:
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
> for char in original:
> except TypeError:
> except ValueError:
> if char in number:
> more = raw_input("Would you like to convert more text or numbers
> if more in 'Yy':
> elif more in 'Nn':
> again = False
> print "Thank you for using Multivert. Multivert will now close"
> import sys
Since this is the end of the program you don't need to
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?
More information about the Tutor