Python 如何正确使用isinstance()命令

Python 如何正确使用isinstance()命令,python,python-3.x,isinstance,Python,Python 3.x,Isinstance,我自己在学习Python,所以我知道我在代码中有很大的错误。欢迎任何建议 这段代码是用于二进制转换器的 isinstance()出现问题。当我尝试代码时,在通过键盘读取的那一刻,它忽略了“if”,直接转到“else” 例如: def convBin(): cont = [] rest = [] dev = [] decimal = [] print("Give me a number: ") valor = input() if isi

我自己在学习Python,所以我知道我在代码中有很大的错误。欢迎任何建议

这段代码是用于二进制转换器的

isinstance()
出现问题。当我尝试代码时,在通过键盘读取的那一刻,它忽略了“if”,直接转到“else”

例如:

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

您可以使用
ast.literal\u eval()
input()
函数返回的字符串解析为由字符串内容表示的对象,这样您就可以使用
isinstance()
按预期测试其类型:

  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.

在Python 3中总是会返回字符串。如果给定的输入不是有效的文本,您可能应该包括一个关于
literal\u eval
将引发的错误的警告。确实如此。按照当时的建议进行了更新。
import ast
while True:
    try:
        valor = ast.literal_eval(input("Give me a number: "))
        break
    except SyntaxError, ValueError:
        print("Please enter a valid number.")