Python Calculator over localhost - Unexpected results when getting result
I'm trying to make a "localhost calculator", where you can send any equation over to the server, and the server will then return the result of the equation. For now i'm just printing the result in the server program.
The Problem
I have a little problem; I get unexpected results, when I run the program. For example: “10 + 45” will evaluate to “65” and that’s not right.
I have a feeling that it’s something simple that I’m missing.
The Code
Here is my code:
The server 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))
The client tmClient.py
:
"""
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()
Any help is highly appreciated.
python
|
show 4 more comments
I'm trying to make a "localhost calculator", where you can send any equation over to the server, and the server will then return the result of the equation. For now i'm just printing the result in the server program.
The Problem
I have a little problem; I get unexpected results, when I run the program. For example: “10 + 45” will evaluate to “65” and that’s not right.
I have a feeling that it’s something simple that I’m missing.
The Code
Here is my code:
The server 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))
The client tmClient.py
:
"""
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()
Any help is highly appreciated.
python
if new_splitted_eq[index+2] == new_splitted_eq[-1]:
You useindex+2
wich will always be out of range when you get near the end of your array. Imagine you have 1 element in your array, at the first pass of the loop you will try to read the second element in your array, that does not exist. Why are ou trying to get theindex+2
element?
– Julien Rousé
Nov 12 '18 at 14:59
@JulienRousé I use index+2 to get the next number after the mathematical sign. But yes, it will get out of range. I just don’t know what to do...
– Laurits L. L.
Nov 12 '18 at 15:21
2
One possible solution would be to add a condition likeif index+2 < len(new_splitted_eq)
beforeif new_splitted_eq[index+2] == new_splitted_eq[-1]:
. Then you need to decide what to do in theelse
case
– Julien Rousé
Nov 12 '18 at 15:24
@JulienRousé Yea, I will do that and see if it works.
– Laurits L. L.
Nov 12 '18 at 16:07
1
It's because you add your first number twice. Oncefinal_result += new_splitted_eq[index-1]
before theif ... else ...
you just added, and once inside theelse
– Julien Rousé
Nov 12 '18 at 20:18
|
show 4 more comments
I'm trying to make a "localhost calculator", where you can send any equation over to the server, and the server will then return the result of the equation. For now i'm just printing the result in the server program.
The Problem
I have a little problem; I get unexpected results, when I run the program. For example: “10 + 45” will evaluate to “65” and that’s not right.
I have a feeling that it’s something simple that I’m missing.
The Code
Here is my code:
The server 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))
The client tmClient.py
:
"""
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()
Any help is highly appreciated.
python
I'm trying to make a "localhost calculator", where you can send any equation over to the server, and the server will then return the result of the equation. For now i'm just printing the result in the server program.
The Problem
I have a little problem; I get unexpected results, when I run the program. For example: “10 + 45” will evaluate to “65” and that’s not right.
I have a feeling that it’s something simple that I’m missing.
The Code
Here is my code:
The server 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))
The client tmClient.py
:
"""
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()
Any help is highly appreciated.
python
python
edited Nov 13 '18 at 12:04
Laurits L. L.
asked Nov 12 '18 at 14:43
Laurits L. L.Laurits L. L.
567
567
if new_splitted_eq[index+2] == new_splitted_eq[-1]:
You useindex+2
wich will always be out of range when you get near the end of your array. Imagine you have 1 element in your array, at the first pass of the loop you will try to read the second element in your array, that does not exist. Why are ou trying to get theindex+2
element?
– Julien Rousé
Nov 12 '18 at 14:59
@JulienRousé I use index+2 to get the next number after the mathematical sign. But yes, it will get out of range. I just don’t know what to do...
– Laurits L. L.
Nov 12 '18 at 15:21
2
One possible solution would be to add a condition likeif index+2 < len(new_splitted_eq)
beforeif new_splitted_eq[index+2] == new_splitted_eq[-1]:
. Then you need to decide what to do in theelse
case
– Julien Rousé
Nov 12 '18 at 15:24
@JulienRousé Yea, I will do that and see if it works.
– Laurits L. L.
Nov 12 '18 at 16:07
1
It's because you add your first number twice. Oncefinal_result += new_splitted_eq[index-1]
before theif ... else ...
you just added, and once inside theelse
– Julien Rousé
Nov 12 '18 at 20:18
|
show 4 more comments
if new_splitted_eq[index+2] == new_splitted_eq[-1]:
You useindex+2
wich will always be out of range when you get near the end of your array. Imagine you have 1 element in your array, at the first pass of the loop you will try to read the second element in your array, that does not exist. Why are ou trying to get theindex+2
element?
– Julien Rousé
Nov 12 '18 at 14:59
@JulienRousé I use index+2 to get the next number after the mathematical sign. But yes, it will get out of range. I just don’t know what to do...
– Laurits L. L.
Nov 12 '18 at 15:21
2
One possible solution would be to add a condition likeif index+2 < len(new_splitted_eq)
beforeif new_splitted_eq[index+2] == new_splitted_eq[-1]:
. Then you need to decide what to do in theelse
case
– Julien Rousé
Nov 12 '18 at 15:24
@JulienRousé Yea, I will do that and see if it works.
– Laurits L. L.
Nov 12 '18 at 16:07
1
It's because you add your first number twice. Oncefinal_result += new_splitted_eq[index-1]
before theif ... else ...
you just added, and once inside theelse
– Julien Rousé
Nov 12 '18 at 20:18
if new_splitted_eq[index+2] == new_splitted_eq[-1]:
You use index+2
wich will always be out of range when you get near the end of your array. Imagine you have 1 element in your array, at the first pass of the loop you will try to read the second element in your array, that does not exist. Why are ou trying to get the index+2
element?– Julien Rousé
Nov 12 '18 at 14:59
if new_splitted_eq[index+2] == new_splitted_eq[-1]:
You use index+2
wich will always be out of range when you get near the end of your array. Imagine you have 1 element in your array, at the first pass of the loop you will try to read the second element in your array, that does not exist. Why are ou trying to get the index+2
element?– Julien Rousé
Nov 12 '18 at 14:59
@JulienRousé I use index+2 to get the next number after the mathematical sign. But yes, it will get out of range. I just don’t know what to do...
– Laurits L. L.
Nov 12 '18 at 15:21
@JulienRousé I use index+2 to get the next number after the mathematical sign. But yes, it will get out of range. I just don’t know what to do...
– Laurits L. L.
Nov 12 '18 at 15:21
2
2
One possible solution would be to add a condition like
if index+2 < len(new_splitted_eq)
before if new_splitted_eq[index+2] == new_splitted_eq[-1]:
. Then you need to decide what to do in the else
case– Julien Rousé
Nov 12 '18 at 15:24
One possible solution would be to add a condition like
if index+2 < len(new_splitted_eq)
before if new_splitted_eq[index+2] == new_splitted_eq[-1]:
. Then you need to decide what to do in the else
case– Julien Rousé
Nov 12 '18 at 15:24
@JulienRousé Yea, I will do that and see if it works.
– Laurits L. L.
Nov 12 '18 at 16:07
@JulienRousé Yea, I will do that and see if it works.
– Laurits L. L.
Nov 12 '18 at 16:07
1
1
It's because you add your first number twice. Once
final_result += new_splitted_eq[index-1]
before the if ... else ...
you just added, and once inside the else
– Julien Rousé
Nov 12 '18 at 20:18
It's because you add your first number twice. Once
final_result += new_splitted_eq[index-1]
before the if ... else ...
you just added, and once inside the else
– Julien Rousé
Nov 12 '18 at 20:18
|
show 4 more comments
1 Answer
1
active
oldest
votes
You are accessing a list with if new_splitted_eq[index+2] == new_splitted_eq[-1]:
wich will always be out of bound if you don't check your index before. If for example your list has 1 item but you try to access the third element, you gonna get an error.
Since you edited your code to reflect the correction in my answer, a second problem is that you use final_result += new_splitted_eq[index-1]
twice, once before the new if else
and once inside the else branch, that's why you get the wrong result in your calculation.
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264546%2fpython-calculator-over-localhost-unexpected-results-when-getting-result%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You are accessing a list with if new_splitted_eq[index+2] == new_splitted_eq[-1]:
wich will always be out of bound if you don't check your index before. If for example your list has 1 item but you try to access the third element, you gonna get an error.
Since you edited your code to reflect the correction in my answer, a second problem is that you use final_result += new_splitted_eq[index-1]
twice, once before the new if else
and once inside the else branch, that's why you get the wrong result in your calculation.
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
add a comment |
You are accessing a list with if new_splitted_eq[index+2] == new_splitted_eq[-1]:
wich will always be out of bound if you don't check your index before. If for example your list has 1 item but you try to access the third element, you gonna get an error.
Since you edited your code to reflect the correction in my answer, a second problem is that you use final_result += new_splitted_eq[index-1]
twice, once before the new if else
and once inside the else branch, that's why you get the wrong result in your calculation.
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
add a comment |
You are accessing a list with if new_splitted_eq[index+2] == new_splitted_eq[-1]:
wich will always be out of bound if you don't check your index before. If for example your list has 1 item but you try to access the third element, you gonna get an error.
Since you edited your code to reflect the correction in my answer, a second problem is that you use final_result += new_splitted_eq[index-1]
twice, once before the new if else
and once inside the else branch, that's why you get the wrong result in your calculation.
You are accessing a list with if new_splitted_eq[index+2] == new_splitted_eq[-1]:
wich will always be out of bound if you don't check your index before. If for example your list has 1 item but you try to access the third element, you gonna get an error.
Since you edited your code to reflect the correction in my answer, a second problem is that you use final_result += new_splitted_eq[index-1]
twice, once before the new if else
and once inside the else branch, that's why you get the wrong result in your calculation.
answered Nov 13 '18 at 14:08
Julien RouséJulien Rousé
75911024
75911024
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
add a comment |
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
Thanks for a very clear answer! I have marked your answer as the right one.
– Laurits L. L.
Nov 13 '18 at 14:29
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264546%2fpython-calculator-over-localhost-unexpected-results-when-getting-result%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
if new_splitted_eq[index+2] == new_splitted_eq[-1]:
You useindex+2
wich will always be out of range when you get near the end of your array. Imagine you have 1 element in your array, at the first pass of the loop you will try to read the second element in your array, that does not exist. Why are ou trying to get theindex+2
element?– Julien Rousé
Nov 12 '18 at 14:59
@JulienRousé I use index+2 to get the next number after the mathematical sign. But yes, it will get out of range. I just don’t know what to do...
– Laurits L. L.
Nov 12 '18 at 15:21
2
One possible solution would be to add a condition like
if index+2 < len(new_splitted_eq)
beforeif new_splitted_eq[index+2] == new_splitted_eq[-1]:
. Then you need to decide what to do in theelse
case– Julien Rousé
Nov 12 '18 at 15:24
@JulienRousé Yea, I will do that and see if it works.
– Laurits L. L.
Nov 12 '18 at 16:07
1
It's because you add your first number twice. Once
final_result += new_splitted_eq[index-1]
before theif ... else ...
you just added, and once inside theelse
– Julien Rousé
Nov 12 '18 at 20:18