-1

Write a program that prompts the user for input of a positive integer n and converts that integer into each base b between 2 and 16 (using a for loop). I'm halfway there (still have to convert the numbers to letters for bases 10+).

When I run the program, the error pops up. I thought int() took integers as parameters?

n = int(input("Enter a positive number: "))

while n < 0:
    n = int(input("Please input a positive number: "))

for x in range(2, 17): #x being the iteration of base numbers
    baseConvert = int(n, x)
    textString = "{} = {} in base {}".format(n, baseConvert, x)
    print(textString)

Traceback (most recent call last):
  File "/tmp/sessions/fdb8f9ea1d4915eb/main.py", line 8, in <module>
    baseConvert = int(n, base)
TypeError: int() can't convert non-string with explicit base
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
Anna Swann
  • 23
  • 2
  • 1
    What do you expect calling `int` with two integer arguments to do? – Brian61354270 Feb 16 '23 at 16:48
  • 1
    Don't cast the `input()` results to int and your code will work fine. – MattDMo Feb 16 '23 at 16:48
  • Please update your question with the full error traceback. – quamrana Feb 16 '23 at 16:49
  • 1
    You can't 'convert' a binary number (which is what an `int` is) to another base. What you can do is to convert an `int` to a `str` as the representation of a number in a particular base. – quamrana Feb 16 '23 at 16:53
  • 1
    Do the answers to this [question](https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-to-a-string-in-any-base) help at all? – quamrana Feb 16 '23 at 16:54
  • @Brian int() should convert the first parameter to the base number of the second parameter – Anna Swann Feb 16 '23 at 16:55
  • No, the `int()` function converts the first parameter (which is already in the base of the second parameter) to an `int`. That is the general pattern of conversion functions: They return a value which is closely related to the name of the function. – quamrana Feb 16 '23 at 16:57

1 Answers1

1

Like this

Credits to https://stackoverflow.com/a/53675480/4954993


BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(number, base):
    res = ""                     #Starts with empty string
    while number and base>1:     #While number is not zero, it means there are still digits to be calculed.
        res+=BS[number%base]     #Uses the remainder of number divided by base as the index for getting the respective char from constant BS. Attaches the char to the right of string res.
        number//= base           #Divides number by base and store result as int in var number.
    return res[::-1] or "0"      #Returns reversed string, or zero if empty.

n=-1
while n < 0:
    n = int(input("Please input a positive number: "))
for i in range(2,17):
    print("Base", i, "Number", to_base(n,i))

Marcus Vdt
  • 122
  • 4