0

I want to code a python calculator, but it goes wrong. Okay, I'll show you my code.

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')
if ans == 'y':
     print('OK! LOADING...')
     sleep(3)
elif ans == 'n':
     print('Oh, you're not going ahead... OK.')
     quit()

num1 = input('Input 1st number')
method = input('Input symbol(+,-,*,/):')
num2 = input('Input 2nd number')
ans = num1+method+num2
print('Answer is ', ans)

And my output....

Calculator v1.0 (Python 3.6.2)
Hello! Are you here for calculating?(y/n)y
OK! LOADING...
Input 1st number1
Input symbol(+,-,*,/):+
Input 2nd number1 
Answer is 1+1.

I want this output:

Calculator v1.0 (Python 3.6.2)
Hello! Are you here for calculating?(y/n)y
OK! LOADING...
Input 1st number1
Input symbol(+,-,*,/):+
Input 2nd number1 
Answer is 2

Somebody HELP!!!!!!!!!

Anton vBR
  • 18,287
  • 5
  • 40
  • 46

12 Answers12

4

I would use the python eval function:

ans = eval(num1+method+num2)

However you must be aware that this is a huge security risk, as it easily allows for code injection from a malicious user.

Stuart Buckingham
  • 1,574
  • 16
  • 25
4

The typical way to do this without eval is to use a dictionary instead of a giant if/elif/else:

import operator # A module of functions that work like standard operators.

# A table of symbols to operator functions. 
op = {'+':operator.add,
      '-':operator.sub,
      '*':operator.mul,
      '/':operator.truediv}

# Make sure to convert the input to integers.
# No error handling here.  Consider if someone doesn't type the correct input.
# This is why eval() is bad.  Someone could type a command to delete your hard disk.  Sanitize inputs!
# In the below cases you will get an exception if a non-integer or
# invalid symbol is entered.  You can use try/except to handle errors.
num1 = int(input('Input 1st number: '))
method = op[input('Input symbol(+,-,*,/):')]
num2 = int(input('Input 2nd number: '))

ans = method(num1,num2)

print('Answer is ', ans)

Output:

Input 1st number: 5
Input symbol(+,-,*,/):/
Input 2nd number: 3
Answer is  1.6666666666666667
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • This answer I liked the most. But I'd use functions to inert my code +1. – Anton vBR Oct 15 '17 at 06:41
  • I added this code on my code and erased from `num1`. But the error code, `Traceback (most recent call last): File "C:\Users\dongjune\Desktop\PyCharm\Calculator.py", line 22, in ans = method(num1,num2) NameError: name 'method' is not defined` –  Oct 15 '17 at 07:58
  • @sjkim104 `method` is defined above between `num1` and `num2`. Did you add that code? – Mark Tolonen Oct 15 '17 at 08:09
1

When you do num1+method+num2 it runs as a concatenation of a string for the method with a number (num1 & num2). What you need to do is actually operate on the two numbers by having different conditions.

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')
if ans == 'y':
     print('OK! LOADING...')
     sleep(3)
elif ans == 'n':
     print("Oh, you're not going ahead... OK.")
     quit()

num1 = int(input('Input 1st number'))
method = input('Input symbol(+,-,*,/):')
num2 = int(input('Input 2nd number'))

if (method == '+'):
    ans = num1 + num2
elif (method == '-'):
    ans = num1 - num2
elif (method == '*'):
    ans = num1 * num2
elif (method == '/'):
    ans = num1 / num2

print('Answer is ', ans)

I changed it so method is an actual operation on the two numbers and used something called "casting" to change the user input of num1 and num2 to integers.

koza
  • 71
  • 1
  • 2
  • 13
1

Your mistake is here:

ans = num1+method+num2

using '+' with variable will just add the variable.

for example:

in your case you added num1+method+num2, which resulted in just 2*2 ect, not the answer.

Here's the solution:

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')
if ans == 'y':
             print('OK! LOADING...')
             sleep(3)
elif ans == 'n':
               print('Oh, you're not going ahead... OK.')
               quit()

num1 = int(input('Input 1st number'))
method = int(input('Press 1 for +,2 for -,3 for *,4 for /: ))
num2 = int(input('Input 2nd number'))
a = num1+num2
b = num1-num2
c = num1*num2
d = mum1/num2
if method==1:
print("If added, the answer will be: ")
print(a)
if method==2:
             print("If subtracted, the answer will be: ")
             print(b)
if method==3:
            print("If multiplied, the answer will be: ")
            print(c)
if method==4:
            print("If divided, the answer will be: ")
            print(d)
else:
     print("Check your input!")
if input("Do you want to repeat (y/n): ") =='n':
                                                exit()
else:
     while True:
           from time import sleep
           print('Calculator v1.0 (Python 3.6.2)')
           ans = input('Hello! Are you here for calculating?(y/n)')
           if ans == 'y':
                         print('OK! LOADING...')
                         sleep(3)
           elif ans == 'n':
                           print('Oh, you're not going ahead... OK.')
                           exit()

           num1 = int(input('Input 1st number'))
           method = int(input('Press 1 for +,2 for -,3 for *,4 for /: ))
           num2 = int(input('Input 2nd number'))
           a = num1+num2
           b = num1-num2
           c = num1*num2
           d = mum1/num2
           if method==1:
                       print("If added, the answer will be: ")
                       print(a)
           if method==2:
                        print("If subtracted, the answer will be: ")
                        print(b)
           if method==3:
                        print("If multiplied, the answer will be: ")
            print(c)
           if method==4:
                        print("If divided, the answer will be: ")
                        print(d)
           else:
                print("Check your input!")
           if input("Do you want to repeat (y/n): ") =='n':
                                                            exit()

This will also repeat the program untill you press n

Faraaz Kurawle
  • 1,085
  • 6
  • 24
  • Welcome to StackOverflow. While this code may answer the question, providing additional context regarding *how* and/or *why* it solves the problem would improve the answer's long-term value. – Sven Eberth Jun 14 '21 at 12:46
  • 1
    oh thx a lot i will edit this answer and will follow your advice in future too. – Faraaz Kurawle Jun 14 '21 at 12:58
1
from tkinter import *
exp = ""
memory = 0

def press(num):
    global exp         #global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.
    exp = exp + str(num) 
    eqn.set(exp)
      
def clear():
    global exp
    exp = ""
    eqn.set(exp)
    
def total():
    global exp
    total = str(eval(exp))  # str- returs as string, eval-evaluates 
    exp = total
    eqn.set(total)
      
def memstore():
    global exp
    global memory
    memory = memory + int(exp)
   
def memrecall():
    global exp
    global memory
    exp = str(memory)
    eqn.set(exp)
      
def memclear():
    global memory
    memory = 0
       
gui=Tk()
gui.title('Calculator')
gui.configure(background = "#F5F5F5")
gui.geometry("357x348")
gui.resizable(0,0)
    
eqn = StringVar()
txt = Entry(gui, textvariable = eqn, bg = 'white', relief = SUNKEN, borderwidth = 5, width = 34)
txt.grid(columnspan = 4, ipadx = 70)
 
button1 = Button(gui,font=('Helvetica',11), text = '1', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(1), height=3, width = 9)
button1.grid(row=4, column= 0)
    
button2 = Button(gui,font=('Helvetica',11), text = '2', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(2), height=3, width = 9)
button2.grid(row=4, column= 1)
        
button3 = Button(gui,font=('Helvetica',11), text = '3', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(3), height=3, width = 9)
button3.grid(row=4, column= 2)

button4 = Button(gui, font=('Helvetica',11), text = '4', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(4), height=3, width = 9)
button4.grid(row=3, column= 0)
    
button5 = Button(gui, font=('Helvetica',11), text = '5', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(5), height=3, width = 9)
button5.grid(row=3, column= 1)

button6 = Button(gui, font=('Helvetica',11), text = '6', fg = 'black',bg = "#eee", cursor = "hand2", command=lambda:press(6), height=3, width = 9)
button6.grid(row=3, column= 2)

button7 = Button(gui, font=('Helvetica',11), text = '7', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(7), height=3, width = 9)
button7.grid(row=2, column= 0)
    
button8 = Button(gui, font=('Helvetica',11), text = '8', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(8), height=3, width = 9)
button8.grid(row=2, column= 1)
    
button9 = Button(gui, font=('Helvetica',11), text = '9', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(9), height=3, width = 9)
button9.grid(row=2, column=2)
    
button0 = Button(gui,font=('Helvetica',11), text = '0', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press(0), height=3, width = 9)
button0.grid(row=5, column= 1)
    
mlt = Button(gui, font=('Helvetica',10,'bold'),text = '╳', fg = 'black', bg = '#E0FFFF', command=lambda:press('*'), height=3, width = 9)
mlt.grid(row=1, column= 3)
    
dvd = Button(gui,font=('Helvetica',10, 'bold'), text = '➗', fg = 'black', bg = '#E0FFFF', command=lambda:press('/'), height=3, width = 9)
dvd.grid(row=4, column= 3)
    
eq = Button(gui, font=('Helvetica',16),text = '=', fg = 'black', bg = '#90EE90', command=total, height=2, width = 6)
eq.grid(row=5, column= 3)
    
add = Button(gui,font=('Helvetica',10, 'bold'), text = '➕', fg = 'black', bg = '#E0FFFF', command=lambda:press('+'), height=3, width = 9)
add.grid(row=2, column= 3)
    
sub = Button(gui,font=('Helvetica',10, 'bold'), text = '➖', fg = 'black', bg = '#E0FFFF', command=lambda:press('-'), height=3, width = 9)
sub.grid(row=3, column= 3)
    
clr = Button(gui,font=('Helvetica',11), text = 'Clear', fg = 'black', bg = '#ADD8E6', command=clear, height=3, width = 9)
clr.grid(row=5, column= 0)
    
dcml = Button(gui,font=('Helvetica',11), text = '◉(dec)', fg = 'black', bg = "#eee", cursor = "hand2", command=lambda:press('.'), height=3, width = 9)
dcml.grid(row=5, column= 2)

memstr = Button(gui,font=('Helvetica',11), text = 'M+', fg = 'black', bg = '#ADD8E6', command=memstore, height=3, width = 9)
memstr.grid(row=1,column= 2)

memr = Button(gui,font=('Helvetica',11), text = 'Mr', fg = 'black', bg = '#ADD8E6', command=memrecall, height=3, width = 9)
memr.grid(row=1,column= 1)

memclr = Button(gui,font=('Helvetica',11), text = 'MC', fg = 'black', bg = '#ADD8E6', command=memclear, height=3, width = 9)
memclr.grid(row=1,column= 0)
  
gui.mainloop()
0

Your operator is just a string, and you are only concatening strings. Check this answer Python:: Turn string into operator on how to convert the input string to operator.

Pavel
  • 785
  • 5
  • 14
0

The variable 'ans' is a string, because it was used in the original input. Thus, when you try to add numbers and strings, it produces a string. That's not the only problem though, the way you are trying to do the calculations is entirely wrong. What you need is an if-elif-else statement for the operation.

Something like this should do it:

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
isCalc = input('Hello! Are you here for calculating?(y/n)')
if isCalc == 'y':
     print('OK! LOADING...')
     sleep(3)
elif ans == 'n':
     print("Oh, you're not going ahead... OK.") # watch out for apostrophes in strings
     quit()

num1 = input('Input 1st number: ')
method = input('Input symbol(+,-,*,/): ')
num2 = input('Input 2nd number: ')
ans = 0
if method == '+':
     ans = num1 + num2
elif method == '-':
     ans = num1 - num2
elif method == '*':
     ans = num1 * num2
elif method == '/':
     ans = num1 / num2

print('Answer is ', ans)

Of course, make sure to fix spacing and stuff. I haven't tested this but it should work.

diggity
  • 118
  • 7
  • Output : `Calculator v1.0 (Python 3.6.2) Hello! Are you here for calculating?(y/n)y OK! LOADING... Input 1st number: 1 Input symbol(+,-,*,/): + Input 2nd number: 1 Answer is 11` –  Oct 15 '17 at 08:01
  • int(input('Input 1st number: ')) (same with second number), sorry my bad – diggity Oct 15 '17 at 08:44
0

Here problem is, it is treating method as a string and it is not able to perform operation specified method. For this, you need to compare the value of the method with an operator.

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')

if ans == 'y':
   print('OK! LOADING...')
   sleep(3)
elif ans == 'n':
   print('Oh, you are not going ahead... OK.')
   quit()

num1 = int(input('Input 1st number\t'))
method = input('Input symbol(+,-,*,/):\t')
num2 = int(input('Input 2nd number\t'))

if method == '+':
    ans = num1 + num2
if method == '-':
    ans = num1 - num2
if method == '*':
    ans = num1 * num2
if method == '/':
    ans = num1 / num2

print('Answer is ', ans)
Satyam Zode
  • 175
  • 4
0
print('Calculator v1.0 (Python 3.6.2)')

ans = input('Hello! Are you here for calculating?(y/n)')

if ans == 'y':
     print('OK! LOADING...')
     sleep(3)

elif ans == 'n':
     print("Oh, you're not going ahead... OK.")
     quit()

num1 = int(input('Input 1st number'))
method = input('Input symbol(+,-,*,/):')
num2 = int(input('Input 2nd number'))


if (method == '+'):
    ans1 = num1 + num2

elif (method == '-'):
    ans1 = num1 - num2

elif (method == '*'):
    ans1 = num1 * num2

elif (method == '/'):
    ans1 = num1 / num2

print('Answer is ', ans1)
Thomas Strub
  • 1,275
  • 7
  • 20
Jiya
  • 745
  • 8
  • 19
0

I think I had the same problem and I solved it like this:

operations = {
    '*': lambda x, y: x * y,
    '/': lambda x, y: x / y,
    '+': lambda x, y: x + y,
    '-': lambda x, y: x - y
}

precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '=': 3}


def calculator(expression, i=0):
    """
    :param expression: like [(1, '+'), (2, '*'), (3, '-'), (4, '=')]
    : i: index of expression from which the calculations start
    :return: int result

    A mathematical expression (1 + 2 * 3 - 4 =), having terms [1, 2, 3, 4]
    and operators ['+', '*', '-', '='] must be converted to list of tuples
    [(1, '+'), (2, '*'), (3, '-'), (4, '=')] and passed as argument.

    Calculates Operation(term_1, operator, term_2) from left to right till
    following operator has higher precedence. If so, calculates last operation
    with result_so_far and recursive call with following_expression, like
    result = Operation(result_so_far, operator, Operation(following_expr)).
    """

    term, operator = expression[i]

    if operator == '=':
        return term
    
    next_i = i + 1
    next_term, next_operator = expression[next_i]
    result = term
    
    while precedence[operator] >= precedence[next_operator]:
        result = operations[operator](result, next_term)
        operator = next_operator
        next_term, next_operator = expression[next_i + 1]
        next_i += 1
    else:
        next_result = calculator(expression, next_i)
        result = operations[operator](result, next_result)

    return result
    

def calculate_input():
    """
    Function to play with calculator in terminal.
    """

    terms = []
    operators = []
    
    def expression_result(terms, operators):
        expression = list(zip(terms, operators+['=']))
        expr_str = "".join(f"{el} " for pair in expression for el in pair)
        result = calculator(expression)

        dashes = "-"*(len(expr_str)+len(str(result))+4)
        return f" {dashes}\n | {expr_str}{result} |\n {dashes}"
   
    while True:
        term = input('Type term and press Enter.\n')
        terms.append(float(term) if '.' in term else int(term))
        print(expression_result(terms, operators))
        operator = input('Type operator and press Enter.\n')
        if operator == '=':
            print(expression_result(terms, operators))
            break
        operators.append(operator)



if __name__ == "__main__":
    calculate_input()

Cosmin Dinu
  • 171
  • 1
  • 4
0
import time , math
print("calculator V1.0 (python 3.6.2)")
ans = input("Hello are you here for calculating y/n")

def calculator():
    num1 = float(input("what is the first number : "))
    method = input(" + - / * : ")
    num2 = float(input("what is the second number : "))

    if method == "+":
        print('the answer is : ',num1 + num2)
    if method == "-":
        print('the answer is : ',num1 - num2)
    if method == "/":
        print('the answer is : ',num1 / num2)
    if method == "*":
        print('the answer is : ',num1 * num2)
    calculator()

if ans == "y" :
    print("ok! loading . . . ")
    time.sleep(3)
    calculator()
if ans == "n" :
    print("oh your not going ahead . . . ok")
    quit()
0

This code works for performing basic calculations using Python

print("Welcome to the Python Calculator")
def addition(n,m):
    print(f"Addition of {n} and {m} is {n+m}")
def subtraction(n,m):
    print(f"Subtraction of {n} and {m} is {n-m}")
def multiplication(n,m):
    print(f"Multiplication of {n} and {m} is {n*m}")
def division(n,m):
    print(f"Division of {n} and {m} is {n/m}")
should_continue=False
while not should_continue:
    n=int(input("Enter the number:"))
    user_input=input("Enter the operation you want to perform\n +\n -\n *\n / \n")
    m=int(input("Enter the number:"))
    if user_input=='+':
       addition(n,m)
    elif user_input=='-':
       subtraction(n,m)
    elif user_input=='*':
       multiplication(n,m)
    elif user_input=='/':
       division(n,m)
    user=input("want to continue type yes if not type no").lower()
    if user=="no":
        should_continue=True
        print("Bye Bye")

Output:

Welcome to the Python Calculator

Enter the number:1

Enter the operation you want to perform

     +

     -

     *

     /  

     selected operation is +

Enter the number:2

Addition of 1 and 2 is 3

You can also perform the same above operations by using the below code. Here I used dictionary to call the Function name.

  def add(n,m):
      return n+m
  def subtraction(n,m):
      return n-m
  def multiplication(n,m):
      return n*m
  def division(n,m):
      return n/m
  operators={
     '+':add,'-':subtraction,'*':multiplication,'/':division
      }
  should_continue=False
  while not should_continue:
      num1=int(input("Enter the number1:"))
      for i in operators:
          print(i)
      print("Enter the any one of the above operator you want to perform")
      user_input=input("")
      num2=int(input("Enter the number2:"))
      function=operators[user_input]
      print(f"{num1} {user_input} {num2} =",function(num1,num2))
      user=input("want to continue type yes if not type no").lower()
      if user=="no":
         should_continue=True
         print("Bye Bye")
halfer
  • 19,824
  • 17
  • 99
  • 186
Prajwal KV
  • 51
  • 6