-1

I've tried to make a ternary calculator on Python, with some other functions like hex, bin, and oct with the built-in functions. There isn't one for ternary so I built one.

def ternary(n):
    e = n/3
    q = n%3
    e = n/3
    q = e%3
    return q

i = int(input("May you please give me a number: "))
print("Binary "+bin(i))
print("Octal "+oct(i))
print("Hexadecimal "+hex(i))
print("Ternary "+ternary(i))
enter code here

But it doesn't work. Why? Where is the problem?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
harmony5
  • 3
  • 1
  • 4
  • You should use `print("Binary " ,bin(i))` instead of `+` because for `+` to work both should be of string or same type. – Kalpesh Dusane Oct 05 '16 at 21:20
  • 2
    Your algorithm for converting to ternary is not even close to correct. You need a loop that repeats the calculations for each digit, and appends them to the result. – Barmar Oct 05 '16 at 21:38

1 Answers1

0

There are a couple of mistakes in your code which others have pointed out in the comments, but I'll reiterate them

  • You are using regular division when you want to use integer division (in Python 3).
  • You are returning an integer from your function whereas bin, oct, and hex all return strings.

In addition, your ternary function is incorrect, even with the errors fixed. The best way to write a function for base conversion on your own is with recursion.

def ternary(n):
    if n == 0:
        return ''
    else:
        e = n//3
        q = n%3
        return ternary(e) + str(q)
Chris Mueller
  • 6,490
  • 5
  • 29
  • 35