You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python简易计算器无法处理含负号的重复运算符运算问题

解决简易计算器重复运算符报错问题

你的代码在处理-4-6、+4+3这类表达式时报错,核心原因是开头的正负号被误识别成了运算运算符。比如输入-4-6时,conta.find("-")会返回第一个字符的索引0,导致conta[0:0]是空字符串,转整数时触发ValueError。

解决方案1:手动处理开头符号

通过先判断输入开头的正负号,再从符号后的位置开始查找运算运算符,避免误判:

print('=====CALCULADORA==========')
conta = input().strip()
operadores = ('+', '-', 'x', '/')

# 处理开头的正负号
start_idx = 0
num_sign = 1
if conta and conta[0] in ('+', '-'):
    num_sign = -1 if conta[0] == '-' else 1
    start_idx = 1

# 从符号后开始查找运算运算符
for op in operadores:
    op_idx = conta.find(op, start_idx)
    if op_idx != -1:
        # 提取左右数值并计算
        left_num = num_sign * int(conta[start_idx:op_idx].strip())
        right_num = int(conta[op_idx+1:].strip())
        
        if op == '+':
            result = left_num + right_num
        elif op == '-':
            result = left_num - right_num
        elif op == 'x':
            result = left_num * right_num
        elif op == '/':
            result = left_num / right_num  # 如需整数除法可改用//
        
        print(f'{left_num} {op} {right_num} = {result}')
        break

解决方案2:使用正则表达式(更简洁可靠)

用正则表达式直接匹配完整的表达式结构,自动区分正负号和运算运算符:

import re

print('=====CALCULADORA==========')
conta = input().strip()

# 正则匹配规则:可选正负号+数字 + 运算符 + 可选正负号+数字
expr_pattern = r'^([+-]?\d+)([+\-x/])([+-]?\d+)$'
match_result = re.match(expr_pattern, conta)

if match_result:
    left = int(match_result.group(1))
    operator = match_result.group(2)
    right = int(match_result.group(3))
    
    # 根据运算符计算结果
    if operator == '+':
        res = left + right
    elif operator == '-':
        res = left - right
    elif operator == 'x':
        res = left * right
    elif operator == '/':
        res = left / right
    
    print(f'{left} {operator} {right} = {res}')
else:
    print('输入格式错误,请输入类似 "3+5" 或 "-4-6" 的表达式')

两种方案都能正确处理-4-6、+4+3、-4+3等所有包含正负号的表达式,正则表达式方案更易扩展和维护。

内容的提问来源于stack exchange,提问作者Gabiloko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:30:55