Why The Variable Didn't Change? - python

I try to make a calculator but when i run it it just show 0. Why my the result variable doesn't change?
MathSlice = list("1 + 2")
i = 0
Number1 = []
Operation = ""
Number2 = []
Result = 0
while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"):
Number1.append(MathSlice[i])
i += 1
Number1 = ''.join(Number1)
Operation = MathSlice[i]
while not i > len(MathSlice):
Number2.append(MathSlice[i - 1])
i += 1
Number2.pop(1)
Number2 = ''.join(Number2)
if Operation == "+":
Result = int(Number1) + int(Number2)
elif Operation == "-":
Result = int(Number1) - int(Number2)
elif Operation == "*":
Result = int(Number1) * int(Number2)
elif Operation == "/":
Result = int(Number1) / int(Number2)
print(Result)
I expect it to printing 3 but the variable result doesn't change and printing 0.

Changes made: while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"): to while not MathSlice[i] in ("+", "-", "*", "/"):
Code:
MathSlice = list("1 + 2")
#print(MathSlice)
i = 0
Number1 = []
Operation = ""
Number2 = []
Result = 0
while not MathSlice[i] in ("+", "-", "*", "/"):
Number1.append(MathSlice[i])
i += 1
Number1 = ''.join(Number1)
Operation = MathSlice[i]
while not i > len(MathSlice):
Number2.append(MathSlice[i - 1])
i += 1
Number2.pop(1)
Number2 = ''.join(Number2)
if Operation == "+":
Result = int(Number1) + int(Number2)
elif Operation == "-":
Result = int(Number1) - int(Number2)
elif Operation == "*":
Result = int(Number1) * int(Number2)
elif Operation == "/":
Result = int(Number1) / int(Number2)
print(Result) #3

what you have done is assume that or statements only act on the second part of the evaluation, however they act on both. Basically this means you are saying is str(MathSlice[i]) == "+" or "-" == True etc. This then instantly cancels the while not loop as strings with characters evaluate as true in python.
The simple fix is to change your while loop from this:
while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"):
to this
while not str(MathSlice[i]) == "+" or str(MathSlice[i]) == "-" or str(MathSlice[i]) == "/" or str(MathSlice[i]) == "*":
which is unfortunately a little bit uglier but it fixes your problem :)

Related

Displaying a friendly error message for dividing by 0

number1_str = input(" First number: ")
number1 = int(number1_str)
number2_str = input("Second number: ")
number2 = int(number2_str)
operation = input("Operation [+, -, *, /]: ")
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
elif operation == "/":
combination = number1 / number2
else:
print(f"Answer: {combination}")
print()
input("Press return to continue ...")
Hi I'm trying to modify this code so that it displays an error message when number2 is zero and you are using the divide function to say "Sorry division by 0 is impossible" or along the lines of that. I'm very new to Python so this might be trivial for some. I've tried try and except statements however no luck. Very eager to learn from all answers!
You can try this:
number1_str = input(" First number: ")
number2_str = input("Second number: ")
operation = input("Operation [+, -, *, /]: ")
operation_list = ["+", "-", "*", "/"]
if operation in operation_list and number1_str.replace(".", "", 1).isnumeric() and number2_str.replace(".", "", 1).isnumeric():
number1 = float(number1_str)
number2 = float(number2_str)
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
else:
if number2 == 0:
combination = "Sorry division by 0 is impossible"
else:
combination = number1 / number2
print(f"Answer: {combination}")
else:
print("Error! Not valid formula")
Use Exception handling try-except can handle any error and if you want to make your own error message using raise keyword.
number1_str = input(" First number: ")
number1 = int(number1_str)
number2_str = input("Second number: ")
number2 = int(number2_str)
operation = input("Operation [+, -, *, /]: ")
try:
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
elif operation == "/":
combination = number1 / number2
else:
print(f"Answer: {combination}")
print()
input("Press return to continue ...")
except ZeroDivisionError:
print("Sorry division by 0 is impossible")

How to program a calculator to follow the order of operation?

I'm new to Python and I'm working on a calculator, it works fine with to numbers but when I input something like 4+3*3 the result is 21 instead of 13, so I want to know how to program my calculator to follow the correct order in which it has to calculate an equation.
operation = input('Enter equation: ').replace(" ", "")
num1 = ""
num2 = ""
operador = ""
op = ["+", "-", "*", "/"]
for char in operation:
if char not in op:
if operador == "":
num1 = num1 + char
else:
num2 = num2 + char
else:
if operador == "":
operador = char
else:
if operador == "+":
num1 = str(float(num1) + float(num2))
elif operador == "-":
num1 = str(float(num1) - float(num2))
elif operador == "*":
num1 = str(float(num1) * float(num2))
elif operador == "/":
num1 = str(float(num1) / float(num2))
operador = char
num2 = ""
if operador == "+":
num1 = str(float(num1) + float(num2))
elif operador == "-":
num1 = str(float(num1) - float(num2))
elif operador == "*":
num1 = str(float(num1) * float(num2))
elif operador == "/":
num1 = str(float(num1) / float(num2))
print(num1)
I think the problem is that you are using a 'for' loop for the input string.
For the example input "4+3*3": first it gets the '4' then the '+' operator and all the other letter from the input string, which doesn't result the correct order of the computation.
Some tutorial for the for loop in python: https://www.w3schools.com/python/python_for_loops.asp
I would try some different approach, like first checking if the input string has '*' or '/' and then calculate with the other operators(of course if the input doesn't have '(' or ')' ).

Repeating a python script in a specific point

I'm currently trying to make a small script which makes basic mathematical operations, and I want it to return to the number input depending if the user want or not to make another operation based on another input. I've already tried while loops and defining a function
Here is the code:
print('Hi!,this is a calculator')
#Here's where it should return
num1 = input('Please,enter a number ')
num2 = input('Enter another number ')
while True:
operator = input('Insert an operator +,-,*,/ ')
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
print('Invalid Operator')
else:
if operator == "+":
result = int(num1) + int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "-":
result = int(num1) - int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "*":
result = int(num1) * int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "/":
result = int(num1) / int(num2)
result = str(result)
print('Your result is ' + result)
exit()
#Here's the repeating input
# repeat = input('Do you want to make another operation? Y/N ')
# repeat = repeat.lower()
# if repeat == 'y' or repeat == 'yes':
# else:
# exit()
You almost had it right. You can use a function to do the calculation, and call the function in a loop. If the user is finished, then break the loop.
EDIT: Added a loop to calculate() per the asker's specifications
print('Hi!, this is a calculator')
def calculate():
# loop in case the user entered an incorrect operator
while True:
num1 = input('Please,enter a number ')
num2 = input('Enter another number ')
operator = input('Insert an operator +,-,*,/ ')
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
print('Invalid Operator')
continue # restart the calculation
else:
if operator == "+":
result = int(num1) + int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "-":
result = int(num1) - int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "*":
result = int(num1) * int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "/":
result = int(num1) / int(num2)
result = str(result)
print('Your result is ' + result)
return # Finished with this calculation
# continuously calculate until the user doesn't say yes
while True:
calculate()
repeat = input('Do you want to make another operation? Y/N ').lower()
if repeat != 'y' and repeat != 'yes':
break
Make two functions and put both functions in a loop.
def calculate(n1,n2):
oper = input("Enter operand: ")
#your if-elif block here
....
....
print("Your result is", ....)
def userInput():
num1 = input("Enter first num: ")
num2 = input("Enter second num: ")
return [num1,num2]
while True:
inlist = userInput()
calculate(inlist[0],inlist[1])
answer = input("Do you want another operation?")
if answer == "Y":
continue
else:
exit()

Creating a basic calculator in python [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 4 years ago.
This is what I have so far:
import sys
first = float(sys.argv[1])
second = str(sys.argv[2])
third = float(sys.argv[3])
if second == "+":
print first + third
elif second == "-":
print first - third
elif second == "*":
print first * third
elif second == "/":
print first / third
elif second == "^":
print first ** third
else:
print "Invalid Operator"
The first and third arguments are supposed to be double floating point numbers. I wasn't sure how the operator is supposed to be represented, so I just named it "second" and set it as a string. I'm confused as to how I'm supposed to actually get the calculations. Are my if/elif/else statements wrong? Am I supposed to use "print" or "return" for actual calculations to be made?
This is an example of a test file:
def test_add(self):
output = self.runScript("simple_calc.py", "1", "+", "1")
result = float(output)
self.assertAlmostEqual(2.0, result, places=10)
output = self.runScript("simple_calc.py", "-1", "+", "1")
result = float(output)
self.assertAlmostEqual(0.0, result, places=10)
output = self.runScript("simple_calc.py", "1.0", "+", "-1.0")
result = float(output)
self.assertAlmostEqual(0.0, result, places=10)
your using = instead of ==
so it should be like this
if second =="+":
and do the same for all
= is an assignment statement not comparison
You could for example make a function called calculator and then use it with user inputs. :
def calculator(x, y, operator):
if operator == "+":
return x + y
if operator == "-":
return x - y
if operator == "*":
return x * y
if operator == "/":
return x / y
The x and y would of course be numbers user would input, operator is the operator of choice. So basically the function here would take 3 arguments.
Here is my solution:
def Operation():
while True:
operation = raw_input('Select operation: \n + = addition\n - = Subtraction\n * = multiplication\n / = Division\n')
if operation.strip() == '+':
break
elif operation.strip() == '-':
break
elif operation.strip() == '*':
break
elif operation.strip() == '/':
break
else:
print "Please select one of the operations"
continue
return operation
def number():
while True:
try:
number = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Please enter valid number: "
return number
num1 = number()
operator = Operation()
num2 = number()
def calculate(num1, operator, num2):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
elif operator == "/":
return num1 / num2
print calculate(num1, operator, num2)

ValueError when trying to convert strings to floating point

I'm having troubles running this program.
It tells me I have a
ValueError: could not convert string to float
The problem is though, that it just skips my input commands and jumps to
print("Invalid Response")
This program works fine on my cellphone but not on my windows 10 laptop.
Any help? Try running it and let me know if it works for you.
def calc(): #The function performing calculation.
if chars == "+":
result = num1 + num2
print (result)
return result
elif chars == "-":
result = num1 - num2
print(result)
return result
elif chars == "*":
result = num1 * num2
print(result)
return result
elif chars == "/":
result = float(num1) / float(num2)
print(result)
return result
else:
print("Invalid or unsupported operation")
cont = ""
def contin():
result = calc()
print("Operate? y/n: ")
cont = input()
if cont == "y":
print(result) # output is: ought to be:
chars = input() #result result
contin_num = float(input())
calc(contin_num) #result operate y/n
print(result, chars, contin_num)
elif cont == "n":
result = 0
print(result)
else:
print ("Invalid response.")
num1 = float(input ())
chars = input ()
num2 = float(input ())
result = 0
while num1 > 0 or num2 > 0:
calc()
contin()
break
if num1 == 0 and num2 == 0:
print("Zero or undefined.")
This is the desired code. I changed a little bit some indentations are wrong in case of contin() function and some logic. Please refer to this if I am wrong in some place do tell me. Thank you
def calc(num1,chars,num2): #The function performing calculation.
if chars == "+":
result = num1 + num2
print (result)
return result
elif chars == "-":
result = num1 - num2
print(result)
return result
elif chars == "*":
result = num1 * num2
print(result)
return result
elif chars == "/":
result = float(num1) / float(num2)
print(result)
return result
else:
print("Invalid or unsupported operation")
cont = ""
def contin(res):
num1 = res
print("Operate? y/n: ")
cont = raw_input()
if cont == "y":
print(num1) # output is: ought to be:
chars = raw_input() #result result
num2 = float(input())
num1=calc(num1,chars,num2) #result operate y/n
print num1
elif cont == "n":
result = 0
print(result)
else:
print ("Invalid response.")
num1 = float(input ())
chars = raw_input ()
num2 = float(input ())
result = 0
while num1 > 0 or num2 > 0:
res = calc(num1,chars,num2)
contin(res)
break
if num1 == 0 and num2 == 0:
print("Zero or undefined.")

Categories