【发布时间】:2023-12-18 03:12:01
【问题描述】:
我以为 '+' 是一个整数,看起来像是一个字符串。
我正在做一个计算器,
这是我的代码:
while True:
said = input("? \n")
symbols = []
for symbol in said.split():
if symbol in ['+','-','*','/']:
symbols.append(symbol)
allobj = said.split()
numbers = []
for number in said.split():
if number.isdigit():
numbers.append(int(number))
length = len(numbers)
if '+' in allobj and length == 2:
result = numbers[0] + int(symbols[0]) + numbers[1]
print("Result ---- " + str(result))
如果我打印1 + 1,它会给我ValueError: invalid literal for int() with base 10: '+'
请帮忙
【问题讨论】:
-
您不能将带有
int(symbols[0])中符号的字符串转换为int。删除+ int(symbols[0]) -
你对
int('+')的结果有什么期望? -
@ZarakiKenpachi 现在呢?新问题 -
TypeError: unsupported operand type(s) for +: 'int' and 'str' -
@mansuetus 真正的加分,例如 1 + 1 = 2
-
@Alex Zab 哦,伙计,尝试自己解决这个问题,在添加之前检查变量类型。检查
numbers[0]和numbers[1]的类型
标签: python string numbers calculator symbols