Benja Marmol
Benja Marmol

Reputation: 1

How to fix " 'int' object is not subscriptable" on this code

I'm setting up a new code on python to convert from the systems hex, oct, bin or decimal. The first action is input a number and their system after that, the console returns the value in the different systems.


import msvcrt

entrada=""
Base="10"
dec=0

def peticion():
    en= input("ingrese el valor numerico: ")
    b= input("ingrese la base del numero ingresado: ")
    decimal= int (str(en), int(b))
    return(en, b, decimal)

def mostrar(b_s, dec, ent):
    sistemas=[hex, int, oct, bin]
    for x in range(len(sistemas)):
        if b_s==sistemas[x]:
            print("usted igreso el numero {} en el sist. {}".format(ent,b_s))
        else:
            print(sistemas[x](int(dec))[2:])

def cal_base(base):
    if base=="10":
        b=int
    elif base=="16":
        b=hex    
    elif base=="8":
        b=oct
    else:
        if base=="2":
            b=bin
    return(b)


entrada, base, dec = peticion()
#print("usted igreso el numero {} con base ({})".format(entrada,base))
b=cal_base(base)
mostrar(b, dec, entrada)

msvcrt.getch()

Upvotes: 0

Views: 112

Answers (1)

Ollin Boer Bohan
Ollin Boer Bohan

Reputation: 2401

This line print(sistemas[x](int(dec))[2:]) only works when sistemas[x] is hex, oct, or bin, all of which return strings with a prefix. When sistemas[x] is int, you will get <some int>[2:], which doesn't work; the int isn't a string, so you can't slice it, and even if you could there is no prefix to remove.

One possible fix is to special-case the code to only remove the prefix when your converted number is a string:

def mostrar(b_s, dec, ent):
    sistemas=[hex, int, oct, bin]
    for x in range(len(sistemas)):
        if b_s==sistemas[x]:
            print("usted igreso el numero {} en el sist. {}".format(ent,b_s))
        else:
            dec_en_sistema = sistemas[x](int(dec))
            if isinstance(dec_en_sistema, str):
                print(dec_en_sistema[2:])
            else:
                print(dec_en_sistema)

And here's an alternate version using try / except (and without the index variable) that should be a bit more pythonic:

def mostrar(b_s, dec, ent):
    sistemas = [hex, int, oct, bin]
    for sistema in sistemas:
        if sistema == b_s:
            print("usted igreso el numero {} en el sist. {}".format(ent, b_s))
        else:
            dec_en_sistema = sistema(int(dec))
            try:
                # elimina el prefijo
                print(dec_en_sistema[2:])
            except TypeError:
                print(dec_en_sistema)

Upvotes: 2

Related Questions