首页 > 解决方案 > 如何检查字典中嵌套列表中的项目是否为浮点数?

问题描述

我目前正在尝试做一些类似计算器的事情,其中​​无效的输入会产生错误。出于本练习的目的,列表中的每个项目都用空格分隔。split() 但是,如果输入是浮点数,我会遇到问题。

我无法导入任何库

def get_valid_numbers(exprlist):
    for n, token in enumerate(exprlist):
        if token.isalpha():
            print(f"Invalid expression, expecting operand between {' '.join(exprlist[:n])} and {' '.join(exprlist[n+1:])} but {exprlist[n]} is a variable")
            return False
        if token != float and token not in '(+-**//)':
            print(f"Invalid expression, expecting operand between {' '.join(exprlist[:n+1])} and {' '.join(exprlist[n+1:])}")
            return False
    return True

我输入了一个浮点数,但它仍然返回错误消息

def main():
    while True:
        expr = input('Enter expression: ')
        if expr == '':
            print('Application ended')
            break
        exprlist = expr.split()
        if get_valid_numbers(exprlist):
             eval(expr)
        else:
             continue

预期的输出是程序将检查令牌是否不是浮点数或不包含运算符和操作数之一“(+-**//)”。如果它是浮点数或包含运算符或操作数之一,则应返回 True

标签: python-3.x

解决方案


检查类型应使用isinstance(). 例如:

a = 5.4
isinstance(a, float)
>>> True

您还可以使用 . 检查类型type()。例如:

b = 2
type(b) is float
>>> False

isinstance()是首选的使用方法。


推荐阅读