python - 我如何正确使用 isinstance()

标签 python python-3.x 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")

我是自学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.

最佳答案

您可以使用 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.")

关于python - 我如何正确使用 isinstance(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52500052/

相关文章:

python - 来自文件的动态字典

python - 列表理解同时迭代两个变量

用于简单递归的Python装饰器?在标准库或其他地方?

python-3.x - 为什么 max() 和 min() 对于 Python 3 中的范围对象不能有效工作?

python - 如何检查token是否为 float ?

python - 如何在 Python 中正确检查对象类型?

Python - isinstance 返回 false

python - 设置 kivy 窗口大小不起作用

python - PySpark - 如何输出具有特定字段的 JSON?

python-3.x - 在 StreamHandler 的 logging.basicConfig 中设置的自定义格式