如何正确使用isinstance()函数?

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

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

这段代码是用来做二进制转换的。

isinstance()出现了问题。当我尝试运行代码时,在键盘输入时它会忽略“if”并直接跳到“else”。

例如:

  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.

5
在Python 3中,input()函数始终返回一个字符串。 - Patrick Haugh
1个回答

1
你可以使用ast.literal_eval()来解析input()函数返回的字符串,将其转换为字符串内容所表示的对象,这样你就可以使用isinstance()测试它的类型,就像你想要的那样:
import ast
while True:
    try:
        valor = ast.literal_eval(input("Give me a number: "))
        break
    except SyntaxError, ValueError:
        print("Please enter a valid number.")

1
你可能应该加上一个警告,提醒用户如果输入的内容不是有效的字面量,literal_eval 将会引发错误。 - Patrick Haugh
确实。按建议更新了。 - blhsing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接