首页 > 解决方案 > 比较两个整数时 if 语句不起作用

问题描述

我正在尝试制作一个python类型的计算器,它允许输入任意数量的数字,它检查是否每隔一个“单词”是一个运算符,但是在比较总和的长度和“单词”的索引时" 它目前正在检查是否应该打印输出,但即使 2 个整数相同,它也不会。

operators = ["+", "-", "/", "*"]

def doSum(sum):
    split = sum.split()
    target = len(split)
    if split[1] in operators and "=" not in "".join(split):
        for WORD in split:
            if split.index(WORD) % 2 != 0:
                if WORD in operators:
                    if int(split.index(WORD)) == int(target):
                        print(eval("".join(split)))
                    else:
                        print(target)
                        print(len(split))
                        print("-=-=-=-=-=-=-=-=-=-=-=-")

doSum("1 + 2")
doSum("3 + 3")
doSum("8 - 4")
doSum("1 + 3 + 3 - 1")

问题行是第 10 - 15 行。我预计输出为:3 6 4 6 但我得到:

3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
7
7 
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-

来自我用于调试的“其他块”

编辑:

感谢@chepner 在评论中提供答案:

“您的 if 条件永远不会为真,因为 split 的索引从 0 运行到 len(split) - 1,并且 target == len(split)。”

标签: pythonpython-3.xif-statement

解决方案


尝试这个,

import ast

>>> def doSum(sum1):
    print(ast.literal_eval(sum1))
    print('-=-=-=-=-=-=-=-=-=-=-=-')


>>> doSum("1 + 2")
3
-=-=-=-=-=-=-=-=-=-=-=-
>>> doSum("3 + 3")
6
-=-=-=-=-=-=-=-=-=-=-=-
>>> doSum("8 - 4")
4
-=-=-=-=-=-=-=-=-=-=-=-
>>> doSum("1 + 3 + 3 - 1")
6
-=-=-=-=-=-=-=-=-=-=-=-

推荐阅读