# This program converts a numeric string (in given base) # to a decimal number (base 10). The range for the base # is limited to 2 <= base <=16 # Also error-checking is done # exercises 5.26 and 5.35 # prints the quick description of the program def greetings(): print 'Greetings!' print 'This program converts a numeric string (in given base)' print 'to a decimal number (base 10).\n The range for the base', print 'is limited to 2 <= base <=16' # get the data and make sure that the user input # correct data def get_data(): while True: base=input('Please, input the base (whole number between 2 and 16, including):') if 2<=base<=16: break else: print 'The base is incorrect. It should be between 2 and 16, including' flag=0 while flag==0: numberString=raw_input('Please, input the number string:') flag=1 for c in numberString: if not c.isdigit(): if ord(c)-87 >= base: flag = 0 break else: if int(c) >= base: flag = 0 break if flag==0: print 'The number string contains illegal characters.' return base,numberString.lower() # make conversion def convert(b,s): string=s[::-1] n=len(string) sum_=0 i=0 for c in string: # iterate over elements of the number string if c.isdigit(): # check if c is a digit n=int(c) else: # if c is not a digit n=ord(c)-87 sum_ += n*(b**i) i +=1 return sum_ def main(): greetings() # prints the quick description of the program # get the data and make sure that the user input # correct data b,s=get_data() # make conversion d=convert(b,s) #display the result print '%s_%d = %d_10' % (s,b,d) main()