简体   繁体   中英

How do i use correctly the isinstance()

def convBin():
    cont = []
    rest = []
    dev = []
    decimal = []

    print("Give me a number: ")
    valor = input()

    if isinstance(valor, int):
        while valor > 0:
            z = valor // 2
            resto = x%2
            valor = valor // 2
            cont.append(z)
            rest.append(resto)

        cont.reverse()
        rest.pop()

        dev.append(cont[1])

        for i in rest:
            dev.append(rest[i])

        print(" ")
        print("Lista de devoluciones: ")
        print(dev)
        print("")

    elif isinstance(valor, float):
        a = valor // 1
        b = valor % 1

        while a > 0:
            z = a // 2
            resto = a%2
            a = a // 2
            cont.append(z)
            rest.append(resto)

        cont.reverse()
        rest.pop()

        dev.append(cont[1])

        for i in rest:
            dev.append(rest[i])

        print("How many decimals do you want?")
        num = input()

        while num > 0:
            dec = b * 1
            dec2 = dec//1
            dec %= 1        
            decimal.append(dec2)


        print("Full part: ")
        print(dev)
        print("Decimal part:")
        print(num)

    else:
        print("An error has appeared")

I'm studying Python on my own, so I know that I have big mistakes in the code. Any advice is welcome.

This code is for a binary converter.

Got a problem with the isinstance() . When I try the code, at the moment that read by keyboard it ignores the "if" and it goes directly to the "else".

For example:

  1. It asks you a number.
  2. It goes to the first if and compare the x type with int(for some reason it is false).
  3. It goes to the `elif` and does the same(check if its float).
  4. Both are false so it goes to else and prints the error.

You can use ast.literal_eval() instead to parse the string returned by the input() function into an object represented by the content of the string, so that you can use isinstance() to test its type as you intended:

import ast
while True:
    try:
        valor = ast.literal_eval(input("Give me a number: "))
        break
    except SyntaxError, ValueError:
        print("Please enter a valid number.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM