我想编写一个python计算器,但它出错了。 好的,我会告诉你我的代码。
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
我想要这个输出:
{{1}}
有人帮助!!!!!!!!!
答案 0 :(得分:3)
没有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
答案 1 :(得分:2)
我会使用python eval
函数:
ans = eval(num1+method+num2)
但是,您必须意识到这是一个巨大的安全风险,因为它很容易允许恶意用户注入代码。
答案 2 :(得分: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()
答案 3 :(得分:0)
您的运算符只是一个字符串,您只是在连接字符串。请查看此答案Python:: Turn string into operator,了解如何将输入字符串转换为运算符。
答案 4 :(得分:0)
变量'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)
当然,请确保修复间距和内容。我没有测试过这个,但它应该可以工作。
答案 5 :(得分:0)
当您执行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的用户输入更改为整数。
答案 6 :(得分:0)
问题是,它将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)
答案 7 :(得分: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)
答案 8 :(得分:0)
尝试我的计算器,它比原来好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()
答案 9 :(得分:0)
我认为我也遇到了同样的问题,我这样解决了它:
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()
答案 10 :(得分:0)
此代码适用于使用 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")
答案 11 :(得分:0)
你的错误在这里:
print(sum(map(int, int(input()))))
在变量中使用 '+' 只会添加变量。
例如:
在您的情况下,您添加了 num1+method+num2,结果只有 2*2 等,而不是答案。
解决办法如下:
ans = num1+method+num2
这也将重复该程序,直到您按 n
答案 12 :(得分:-1)
print("Calculator v1.0 (Python 3.6.2)")
yes_or_no=input("Hello! Are you here for calculating?(y/n)")
if yes_or_no == 'y':
while True:
noone=input("Input 1st number : ")
method=input("Input symbol(+,-,*,/) : ")
notwo= input("Input 2nd number : ")
nuummbbeer=(noone+method+notwo)
given_number=nuummbbeer
given_number_in_string=str(given_number)
position_of_multiplication=(given_number_in_string.find("*"))
position_of_addition=(given_number_in_string.find("+"))
position_of_substraction=(given_number_in_string.find("-"))
position_of_division=(given_number_in_string.find("/"))
if position_of_multiplication >= 0:
position_of_multiplication=(given_number_in_string.find("*"))
first_no=float(given_number_in_string[0:position_of_multiplication])
second_no=float(given_number_in_string[position_of_multiplication+1:16])
print(f"answer is : {first_no*second_no}")
a=input("")
elif position_of_addition >= 0:
position_of_addition=(given_number_in_string.find("+"))
first_no=float(given_number_in_string[0:position_of_addition])
second_no=float(given_number_in_string[position_of_addition+1:16])
print(f"answer is : {first_no+second_no}")
s=input("")
elif position_of_substraction >= 0:
position_of_substraction=(given_number_in_string.find("-"))
first_no=float(given_number_in_string[0:position_of_substraction])
second_no=float(given_number_in_string[position_of_substraction+1:16])
print(f"answer is : {first_no-second_no}")
s=input("")
elif position_of_division >= 0:
position_of_division=(given_number_in_string.find("/"))
first_no=float(given_number_in_string[0:position_of_division])
second_no=float(given_number_in_string[position_of_division+1:16])
print(f"answer is : {first_no/second_no}")
s=input("")
else:
print("Exiting")
答案 13 :(得分:-1)
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()