如何编写 python 计算器

how to code a python calculator

我想编写一个 python 计算器,但是出错了。 好的,我给你看我的代码。

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)

还有我的输出....

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.

我想要这个输出:

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

有人帮助!!!!!!!!!

您的运算符只是一个字符串,您只是连接字符串。检查此答案 Python:: Turn string into operator,了解如何将输入字符串转换为运算符。

我会使用 python eval 函数:

ans = eval(num1+method+num2)

但是您必须意识到这是一个巨大的安全风险,因为它很容易允许恶意用户注入代码。

变量'ans'是一个字符串,因为它是在原始输入中使用的。因此,当您尝试将数字和字符串相加时,它会生成一个字符串。 但这不是唯一的问题,您尝试进行计算的方式是完全错误的。您需要的是操作的 if-elif-else 语句。

应该这样做:

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)

当然,请确保修复间距和内容。我还没有测试过这个,但它应该可以工作。

当您执行 num1+method+num2 时,它会作为方法的字符串与数字 (num1 & num2) 的串联运行。你需要做的就是通过不同的条件对两个数字进行实际操作。

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)

我更改了它,所以方法是对这两个数字的实际操作,并使用一种叫做“casting”的东西将 num1 和 num2 的用户输入更改为整数。

这里的问题是,它将 method 视为一个字符串,它无法执行指定的操作 method。为此,您需要将 method 的值与运算符进行比较。

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)

在没有 eval 的情况下执行此操作的典型方法是使用字典而不是巨型 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)

输出:

Input 1st number: 5
Input symbol(+,-,*,/):/
Input 2nd number: 3
Answer is  1.6666666666666667
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)

试试我的计算器,它好 100 倍,容易 10 倍

from math import *

def example():
    example_i = input("\nExample: ")
    math(example_i)

def math(example_i):
    print(example_i,"=",eval(example_i))
    example()
example()

我想我遇到了同样的问题,我是这样解决的:

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()

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()

此代码适用于使用 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")

输出:

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

您也可以使用以下代码执行与上述相同的操作。这里我用字典来调用函数名

  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")

你的错误在这里:

ans = num1+method+num2

对变量使用“+”只会添加变量。

例如:

在您的情况下,您添加了 num1+method+num2,结果只有 2*2 等,而不是答案。

解决方法如下:

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()

这也会重复该程序,直到您按下 n

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()