python - 比较两个整数时 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)。”
解决方案
尝试这个,
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
-=-=-=-=-=-=-=-=-=-=-=-
推荐阅读
- php - PHP - 如何读取 json 文件头和其他对象并插入 mysql
- objective-c - NSURLConnection 总是 TRUE
- python - 自动化无根安卓智能手机
- javascript - 使用从 ajax 请求返回的数据更新输入“值”属性...传入 [object, Object]。- Django/Python
- c - atomic operator++ 和 atomic_fetch_add_explicit 的区别
- python - 如何在布尔变量上使用 .trace?
- swift - 如何更快地显示来自 Firebase 的数据?
- r - 如何让R函数返回多个参数值
- python-3.x - 从 PyQt4 迁移到 PyQt5
- css - 在 RMarkdown 文档中为 fontcolor 创建与输出无关的标记