I am trying to add the value of "next_answer" to current_answer anytime a new calculation is done but when I run the code the next_answer doesn't get added to the current_answer.
Did I position the "current_answer += next_answer" wrongly? Please help me:)
#calculator
#Add
def add(n1, n2):
return n1 + n2
#subtract
def subtract(n1, n2):
return n1 - n2
#multiply
def multiply(n1, n2):
return n1 * n2
#divide
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*":multiply,
"/":divide,
}
num1 = int(input("What is the first number?: "))
for operation in operations:
print(operation)
select_operator = input("Which operator do you want? Type +, - * or /")
num2 = int(input("What is the next number?: "))
operation_function = operations[select_operator]
answer = operation_function(num1, num2)
print(f"{num1} {select_operator} {num2} = {answer}")
continue_ = True
while continue_:
current_answer = answer
next_calculation = input(f"Type 'y' to continue calculating with
{current_answer} or type 'n' to exit.:")
if next_calculation == "y":
select_operator = input("Which operator do you want? Type +, - * or /")
next_number = int(input("What is the next number?:"))
operation_function = operations[select_operator]
next_answer = int(operation_function(current_answer, next_number))
print(f"{current_answer} {select_operator} {next_number} = {next_answer}")
current_answer += next_answer
elif next_calculation == "n":
continue_ = False
print("Thanks for using my calculator")
Note that every time you go through the while loop, you set current_answer to be answer, which is the first answer. So you are overriding your update to the first calculation.
See line current_answer = answer.
Some of the content has been simplified, so refer to it as appropriate:
operations = {"+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y}
select_operator = input("Which operator do you want? Type: +, - * or /:")
num1 = int(input("What is the first number?: "))
num2 = int(input("What is the next number?: "))
answer = operations[select_operator](num1, num2)
print(f"{num1} {select_operator} {num2} = {answer}\n")
while True:
next_calculation = input(f"Type 'y' to continue calculating with {answer} or type 'n' to exit.:")
if next_calculation == "y":
preview_answer = answer
select_operator = input("Which operator do you want? Type: +, - * or /:")
next_number = int(input("What is the next number?:"))
answer = operations[select_operator](answer, next_number)
print(f"{preview_answer} {select_operator} {next_number} = {answer}")
else:
print("Thanks for using my calculator")
exit()
print()
Related
I am here trying to just make a simple calculator in python, and I wonder if its possible to make the 3 first lines in to one line when command run. What I mean with that is; I don't have to press enter to type the next number/operator but press space instead (in the input section).
while True:
import operator
num1 = int(input("Whats the first number:"))
oper = input("Which operator would you like to use: (+,-,/,*,**,^) :")
num2 = int(input("Whats the second number:"))
if oper == "+":
x = operator.add
elif oper == "-":
x = operator.sub
elif oper == "*":
x = operator.mul
elif oper == "/":
x = operator.__truediv__
elif oper == "**":
x = operator.pow
elif oper == "^":
x = operator.xor
else:
print("invalid input")
print(num1,oper,num2,"=",x(num1,num2))
You can use the split method of Python strings to accomplish this. Note that this code depends on three objects, separated by spaces, being entered. If more or fewer are entered or the spaces are forgotten, or either "number" is not actually an integer, there will be an error.
print("Enter a number, a space, an operator, a space, and another number.")
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)
Rory's answer and comments pointed on the right direction, but here's a practical example:
operators = ["+","-","/","*","**","^"]
msg = f"Example query: 8 * 4\nAllowed operators: {', '.join(operators)}\nType your query and press enter:\n"
x = input(msg)
cmd_parts = [y.strip() for y in x.split()] # handles multiple spaces between commands
while len(cmd_parts) != 3: # check if lenght of cmd_parts is 3
x = input(msg)
cmd_parts = [y.strip() for y in x.split()]
# verification of command parts
while not cmd_parts[0].isdigit() or not cmd_parts[2].isdigit() or cmd_parts[1] not in operators :
x = input(msg)
cmd_parts = [y.strip() for y in x.split()]
num1 = cmd_parts[0]
oper = cmd_parts[1]
num2 = cmd_parts[2]
res = eval(f"{num1} {oper} {num2}")
print(num1,oper,num2,"=", res)
Python Example (Enable Interactive mode)
calc=input("type here:- ").split()
# type belove with space between
num1,operatoe,num2=calc[:]
# if length of calc doesn't equal to three you can continue with while loop
print(num1,operator,num2)
An improved working calculator which handles some errors based on other answers:
import operator
x = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.__truediv__,
"**": operator.pow,
"^": operator.xor
}
while True:
print("Enter a number, a space, an operator, a space, and another number.")
try:
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)
print(num1,oper,num2,"=",x[oper](num1,num2))
except:
print("invalid input")
I am very new to Python but I wanted to code an calculator. It works fine exept for the sqrt function. Everytime I try to calculate the square root of a number I get the error message.
I know that there are probably thousand ways to code a better calculator but I would really like to know what I did wrong and how I can fix this.
This is my code:
import math
no1 = float(input('Insert a number: '))
operator = input("Operator: ").upper()
result = no1
while operator != "=":
if (operator) == "-":
no2 = float(input('Insert next number: '))
result = result - no2
operator = input("Operator: ").upper()
elif (operator) == "/":
no2 = float(input('Insert next number: '))
result = result / no2
operator = input("Operator: ").upper()
elif (operator) == "+":
no2 = float(input('Insert next number: '))
result = result + no2
operator = input("Operator: ").upper()
elif (operator) == "*":
no2 = float(input('Insert next number: '))
result = result * no2
operator = input("Operator: ").upper()
elif (operator) == "^":
no2 = float(input('Insert next number: '))
result = math.pow(result,no2)
operator = input("Operator: ").upper()
elif (operator) == "sqrt":
result = math.sqrt(no1)
else:
print('Error!')
operator = "="
print(result)
Thank you very much!
You convert the operator to upper case but the elif has lower case 'sqrt'.
Change it to
elif (operator) == "SQRT":
result = math.sqrt(no1)
You are converting the input to a uppercase, but then testing for 'sqrt'. Test for 'SQRT' instead. You will also want to remove the while loop otherwise it will never exit.
Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
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)
I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
I am not able to do two operations at once either.
Use functions from the operator module or simple functions you define yourself to the calculation work, then map the operation name from the queencommand string to those functions:
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
operator.add could be replaced by lambda a, b: a + b, etc. if you don't want to use a module for those operations.
Here is a fully fledged calculator. See if it helps:
def multiplication():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 * num2
print(ans)
def addition():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 + num2
print(ans)
def subtraction():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 - num2
print(ans)
def division():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 / num2
print(ans)
def Help():
print("""Welcome to Calculator P1!!!
Type "x" for multiplication.
Type "+" for addition.
Type "-" for subtraction.
Type "/" for division.""")
while True:
print("Type 'help' for introduction or instructions")
choice = input("Operator: ")
if choice == "x" or choice == "muliplication":
multiplication()
elif choice == "+" or choice == "addition":
addition()
elif choice == "-" or choice == "subtraction":
subtraction()
elif choice == "/" or choice == "division":
division()
elif choice == "help":
Help()
answer = input('Run again? (y/n): ')
if answer == 'n':
break
elif answer == 'y':
continue
else:
print("""Unrecognized Input.
<<<<RESTARTING PROGRAM>>>>""")
continue