int() can't convert non-string with explicit base – Why?

Question:

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
Asked By: Anna Swann

||

Answers:

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))

Answered By: Marcus Vdt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.