0

I'm trying to write code that will take any decimal value and then convert it to any input base.

I've created an infinite loop and I've read through suggested similar questions but I just cannot work it out.

Any assistance would br really appreciated, I'm a major python rookie (obviously).

decimal = int(input("Enter a decimal number to be converted: "))
new_base = int(input("Enter the base you wish to convert to: "))
 
def base_conversion(decimal, new_base):
    output = []
    quotient = -1
    while quotient != 0:
        remainder = decimal % new_base
        quotient = int(decimal / new_base)        
        output.insert(0, remainder)        
    return output
    result = output
    print(result)
 
base_conversion(decimal, new_base)
Sessamel
  • 1
  • 3
  • `quotient` is assigned the value of `dec_num / new_base` each iteration of the loop. `dec_num` and `new_base` never change their values within the loop, so the result of that division will always yield the same number. As long as the result of this division is not zero, the loop will continue, since `quotient` will always have the same non-zero value. – Paul M. Jun 24 '20 at 12:42
  • Also, `return` exits the function; the last two lines of your function will never execute. – chepner Jun 24 '20 at 12:44
  • For efficiency reasons, you should *append* the remainder to the list, then reverse the list before returning it. (Or instead of `list`, use `collections.deque`, which supports efficient prepending.) – chepner Jun 24 '20 at 12:46
  • @chepner Thanks! Though for the last few lines, don't I need to return the value before I can print it? – Sessamel Jun 24 '20 at 13:07
  • No; if you are printing from the function, you don't need to return it at all. But the function is more flexible if you *just* return the value, and let the caller print it *if* it wants to. – chepner Jun 24 '20 at 13:09

2 Answers2

0

You keep dividing dec_num, which never changes, by new_base. Your code will either exit after one iteration, or never, depending on whether newbase divides dec_num or not. The idea is that you always divide the current quotient at each iteration. Also, you can use divmod to get the quotient and the remainder at the same time.

quotient = dec_num
while not quotient:
    quotient, remainder = divmod(quotient, new_base)
    ...
chepner
  • 497,756
  • 71
  • 530
  • 681
0

I guess the reason why its because you set the quotient to -1 before the while loop and so it won't change and be always different than 0, causing a infinite loop. Im a rookie aswell btw. I hope I'm right and helped. :)