Python basic questions) essence conversion program) int() can't convert non-string with explicit base

Asked 2 years ago, Updated 2 years ago, 119 views

select= int (input("decision of decimal (16/10/8/2):")
num=input ("Enter Value:")

if select !=2 and select != 8 and select != 16 and select != 10 :
     print("Please enter only one of the 16,10,8,2 numbers")
     exit()

elif select == 16:
     num10=int(num,16)
elif select == 10:
     num10=int(num,10)
elif select == 8:
     num10=int(num,8)
elif select == 2:
     num10=int(num,2)


print ("hex ==>", hex(num10))
print ("decimal ==>", num10)
print("Hex ==>", oct(num10))
print("Binary ==>", bin(num10))

# num10="(Because it is 16=hex=str?)_
select= int (input ("decide the decimal (16/10/8/2):"))
num=int ("Enter Value:")

if select == 16:
     num10=int(num,16)
elif select == 10:
     num10=int(num,10)
elif select == 8:
     num10=int(num,8)
elif select == 2:
     num10=int(num,2)
else :
     print("Please enter only one of the 16,10,8,2 numbers")
     exit()

print ("hex ==>", hex(num10))
print ("decimal ==>", num10)
print("Hex ==>", oct(num10))
print("Binary ==>", bin(num10))

How should I correct it and where is it wrong? I don't know why both codes can't run,,,

python base-conversion

2022-09-22 08:23

2 Answers

First of all, the reason for the error is that num is numeric. num=input("Enter value:")

Python versions 2 and 3 are a little different, and in 2.x, input judged the data type, but in 3.x, input is just a string.

int (character, numeric), or int ('A', 16), is 10.


2022-09-22 08:23

Thank you! You don't have to take num as a number, you just have to take it! I modified it like this

sel = int("Determine input variable (16/10/8/2) :")

sel = int("Determine input variable (16/10/8/2) :")



if (sel != 2) and (sel != 8) and (sel != 10) and (sel != 16):
    print("Please enter only one of the 16,10,8,2 numbers!")
    exit()

num = input ("Enter value: ")
print("numtype ==>", type (num))
if sel == 2 :
    num10 = int(num,2)
if sel == 8 :
    num10 = int(num,8)
if sel == 10 :
    num10 = int(num,10)
if sel == 16 :
    num10 = int(str(num),16)


print("Hex ===> %s" %hex(num10))
print("decimal ===> %d" %num10)
print("Hex ===> %s" %oct(num10))
print("Binary ===> %s" %bin(num10))


2022-09-22 08:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.