Advertisement
bwukki

Untitled

Dec 1st, 2017
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. """
  2. by Curtis Michels for cs160 @ COCC
  3. v0.001 date: 11/30/2017
  4. """
  5. import math
  6.  
  7. #checks if user input is an integer, will continue asking until they enter one
  8. def getinput():
  9.     while True:
  10.         try:
  11.             out = int(input())
  12.         except ValueError:
  13.             print("Please only enter integers")
  14.             continue
  15.         else:
  16.             return out
  17.  
  18. def convertDecToBase(num,base):
  19.     #takes a number from base 10 and converts it to the specified base, prints & returns the result
  20.     i = 0
  21.     num = int(num)
  22.     base = int(base)
  23.     #figuring out how many places in the new base the number needs to take up
  24.     while True:
  25.         if (num / base**i < 1):
  26.             if (i == 1):
  27.                 print(chr(num+55))
  28.                 return(0)
  29.             highPow=i-1
  30.             #print('The highest power of base', base, 'that goes into',num,'is', highPow)
  31.             break
  32.         i = i+1
  33.  
  34.     x = ''
  35.     #loop is written in such a way that it counts down instead of up so the digits are in the proper order
  36.     i = highPow
  37.     while i >= 0:
  38.         #replaces the digit with a corresponding letter if it's >= 10
  39.         if (num//base**i >= 10):
  40.             x = x+chr(num//base**i+55)
  41.         #otherwise just put the regular number in
  42.         else:
  43.             x = x+str(num//base**i)
  44.         num = num%base**i
  45.         i = i-1
  46.     #this is just to handle the situation where the number is less than the base being converted to
  47.     if(num != 0):
  48.         x = x[:-1]
  49.         print(x+chr(num+55))
  50.         return(x+chr(num+55))
  51.     else:
  52.         print(x)
  53.         return(x)
  54.  
  55. def main():  
  56.     print('Please input a decimal number ')
  57.     x = getinput()
  58.     print('Please input a base to convert the number to ')
  59.     y = getinput()
  60.     convertDecToBase(x,y)
  61.  
  62. main()
  63.  
  64. #runs again if the user wants it to
  65.  
  66. while True:
  67.     x = input('Convert another number? Y/N ')
  68.     if (x == 'Y' or x == 'y'):
  69.         main()
  70.     else:
  71.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement