本地主机上的Python计算器-获取结果时出现意外结果

本地主机上的Python计算器-获取结果时出现意外结果,python,Python,我正在尝试制作一个“localhost计算器”,您可以将任何等式发送到服务器,然后服务器将返回等式的结果。现在我只是在服务器程序中打印结果 问题 我有一个小问题;当我运行程序时,我得到了意想不到的结果。例如:“10+45”将评估为“65”,这是不对的 我有一种感觉,这是我错过的简单的东西 代码 这是我的密码: 服务器tmServer.py: """ This is the server, that hosts the connection between the client and

我正在尝试制作一个“localhost计算器”,您可以将任何等式发送到服务器,然后服务器将返回等式的结果。现在我只是在服务器程序中打印结果

问题 我有一个小问题;当我运行程序时,我得到了意想不到的结果。例如:“10+45”将评估为“65”,这是不对的

我有一种感觉,这是我错过的简单的东西

代码 这是我的密码:

服务器
tmServer.py

"""
   This is the server, that hosts the connection between the client
   and the server.
   This server stores the clients math equation, finds out what kind
   of equation it is, and returns back the final answer to the equation.
"""

import socket
import sys

import exceptions as exc

# Socket for creating a connection.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ''

# Try getting the port from the commandline.
try:
    port = int(sys.argv[1])
except IndexError:
    err = True
else:
    err = False

# If err is True, no argument is provided.
# Raise exception.
if err == True:
    msg = "You can't run this in the main with no port argument!"
    raise exc.RunningInMainFileOrNoArgumentException(msg)

# Host the connection with s.bind()
s.bind((host, port))

# Listen after request for connection
# and if so, accept connection.
s.listen(1)
print("Waiting for connection with client...")
conn, addr = s.accept()
print("Client is at", str(addr))

# Get the raw math equation from client.
client_data = conn.recv(100000)

# Decode the data to string.
decoded_data = client_data.decode()

# Split the lines into understandable characters,
# and make all the numbers integer.
splitted_eq = decoded_data.split(' ')
new_splitted_eq = []
for item in splitted_eq:
    try:
        new_splitted_eq.append(int(item))
    except ValueError:
        # If not a number, just append.
        new_splitted_eq.append(item)

# Use this variable, for knowing when to check for math signs.
last_was_num = False
done = False

final_result = 0
checking_signs = ['+', '-', '*', '/']

# Then, go through the new list.
for index, item in enumerate(new_splitted_eq):
    if type(item) == int:
        # Then it's a number.
        # Set last_was_num to True.
        last_was_num = True
        # Loop back.
        continue
    if last_was_num == True:
        # Check for math signs.
        for sign in checking_signs:
            if item == sign:
                if item == '+':
                    # Just add the last number to the final_result.
                    final_result += new_splitted_eq[index-1]

                    # Check that the index does not exceed the lists boundaries.
                    if index+2 < len(new_splitted_eq):
                        if new_splitted_eq[index+2] == new_splitted_eq[-1]:
                            # Then it's the last number in the list.
                            # Just add it, and break.
                            final_result += new_splitted_eq[index+2]
                            break
                    else:
                        # Then it's the last two numbers.
                        final_result += new_splitted_eq[index-1]
                        final_result += new_splitted_eq[-1]


# Print the final result, for now.
# Next step, is to send it back to the client.

# But there are unexpected outputs, 
# it's plussing the first number in the equation
# at the last iteration, so fx:
# 10 + 45 = 65
print(str(final_result))
"""
   This is the client that is sending the raw math equation
   to the server.
"""

import socket
import sys

import exceptions as exc

# Create socket.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server via. locahost.
host = '127.0.0.1'

# Try getting the port from the commandline.
try:
    port = int(sys.argv[1])
except IndexError:
    err = True
else:
    err = False

# If err is True, no argument is provided.
# Raise exception.
if err == True:
    msg = "You can't run this in the main or with no port argument!"
    raise exc.RunningInMainFileOrNoArgumentException(msg)

# Ask for connection.
s.connect((host, port))

# Ask for an equation by the user.
equation = input("Write an equation with spaces to seperate: ")

# Send the equation to the server, for evaluation.
s.send(str(equation).encode())

# Read the answer.
i = 0
# Make the final result an empty string.
eq_result = ''

while(True):
    # Ask for the data.
    # Allow the client to read up to 100.000 bytes.
    data = s.recv(100000)
    # To minimize lag, read the output in chunks.
    if i < 5:
        eq_result += str(data.decode())

    # If the output is done;
    # break out of loop.
    if not data:
        break

# Print the equations result.
if eq_result:
    print("The answer to " + equation + " is equal to " + eq_result)
else:
    print("No result has been returned. Please try again later.")

# Finally, terminate the connection with the server.
s.close()

非常感谢您提供的任何帮助。

您访问的列表中包含
如果新的分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割分割。例如,如果您的列表有1个项目,但您尝试访问第三个元素,您将得到一个错误


由于您编辑了代码以反映我的答案中的更正,第二个问题是您使用了两次
final\u result+=new\u splitted\u eq[index-1]
,一次在new
if-else
之前,一次在else分支内部,这就是您在计算中得到错误结果的原因。

if-new\u splitted\u eq[index+2]==new_splitted_eq[-1]:
您使用的
索引+2
当您接近数组末尾时,它将始终超出范围。假设数组中有1个元素,在循环的第一个过程中,您将尝试读取数组中不存在的第二个元素。你为什么要尝试获取
索引+2
元素?@julienrusé我使用索引+2来获取数学符号后的下一个数字。但是是的,它会超出范围。我只是不知道该怎么办……一个可能的解决方案是在
if new_splitted_eq[index+2]==new_splitted_eq[-1]:
之前添加一个类似于
if index+2
的条件。然后,您需要决定在
else
案例中要做什么,因为您将第一个数字添加了两次。如果。。。else…
您刚刚添加的,一旦进入
else
中,如果您只进行数学计算,则会有一个预定义的函数eval(),感谢您提供了非常清晰的答案!我已把你的答案标为正确答案。