我正在为我的介绍编程课程编写一个程序,我需要制作一个计算器来打印结果,就像历史一样。我这样做的方式是第一个数字,算术运算和第二个数字是列表中的单独对象,但我需要将它们组合成列表中的完整对象。我已经尝试了几种方法来做到这一点,但每次都会崩溃或者不能正常工作。
history = []
first_number = int(input("please input your first number"))
second_number = int(input("please input your second number"))
operator = input("ADD, SUBTRACT, DIVIDE, MULTIPLY, CHOOSE again or STOP? ").lower()
def add():
return(first_number + second_number)
def problemAdd():
return(first_number, "+", second_number)
while operator != "stop":
if operator == "add":
print("the problem was:", first_number, "+", second_number, "=", add())
history.append (problem())
print(history)
first_number = int(input("please input your first number"))
second_number = int(input("please input your second number"))
operator = input("ADD, SUBTRACT, DIVIDE, MULTIPLY, CHOOSE again or STOP? ").lower()
现在这部分代码我希望它足以发现问题。这就是它的结果:
please input your first number2
please input your second number2
would you like to ADD, SUBTRACT, DIVIDE, MULTIPLY, CHOOSE again or STOP? add
the problem was: 2 + 2 = 4
[(2, '+', 2)]
please input your first number1
please input your second number2
would you like to ADD, SUBTRACT, DIVIDE, MULTIPLY, CHOOSE again or STOP? add
the problem was: 1 + 2 = 3
[(2, '+', 2), (1, '+', 2)]
please input your first number
我经历了两次,以显示每个问题的显示方式。
答案 0 :(得分:2)
# lst = [(2, '+', 2)]
for tpl in lst:
operation = " ".join(map(str,tpl))
# map(str, tpl) returns an object where every element in tpl is mapped
# using the str function. str(object) returns the value of object as a
# string.
result = eval(operation)
# eval IS A BAD IDEA, BUT SIMPLE TO IMPLEMENT
print("{} = {}".format(operation, result))
如果这是你正在尝试做的事情,我们有点不清楚。我不确定你问题中[ ..., "3 - 2 = 1"]
部分的来源。也许这会有所帮助吗?
如果您只有两个操作数和一个运算符(例如,所有内容都是a ? b
形式,其中?
是运算符,那么这样更安全:
def do_operation(operation):
import operator
operand_1, operator, operand_2 = operation
try:
f = {"+": operator.add, "-": operator.sub,
"/": operator.truediv, "*": operator.mul,
"//": operator.floordiv, "%": operator.mod}[operator]
except KeyError:
raise ValueError("Invalid operator")
return f(operand_1, operand_2)
for tpl in lst:
operation = " ".join(map(str,tpl))
result = do_operation(tpl)
print("{} = {}".format(operation, result))
history = []
first_number = int(input("please input your first number"))
second_number = int(input("please input your second number"))
# what do you do if the user doesn't enter a number? Your program crashes
operator = input("ADD, SUBTRACT, DIVIDE, MULTIPLY, CHOOSE again or STOP? ").lower()
op_mapping = {"add":"+", "subtract":"-", "divide":"/", "multiply":"*"}
if operator in op_mapping: # this will exclude 'choose' and 'stop'
operator = op_mapping[operator]
elif operator == 'choose': # handle it
elif operator == 'stop': # handle it, these are up to you
else: # invalid input, handle it.
# NEW
operation = (first_number, operator, second_number)
# this makes it easier to refer to all three at once.
def calculate(operation):
"""Calculates the result based on which operator is used"""
import operator
operand_1, operator, operand_2 = operation
try:
f = {"+": operator.add, "-": operator.sub,
"/": operator.truediv, "*": operator.mul,
"//": operator.floordiv, "%": operator.mod}[operator]
except KeyError:
raise ValueError("Invalid operator")
return f(operand_1, operand_2)
## while operator != "stop": # you're gonna handle this above
## if operator == "add": # we modified it so our mapping handles all if cases
## print("the problem was:", first_number, "+", second_number, "=", add())
## history.append (problem())
## print(history)
## first_number = int(input("please input your first number"))
## second_number = int(input("please input your second number"))
## operator = input("ADD, SUBTRACT, DIVIDE, MULTIPLY, CHOOSE again or STOP? ").lower()
human_readable = " ".join(map(str,operation))
history.append(human_readable)
print("{} = {}".format(human_readable, calculate(operation))
print(history)
# LOOP AS NEEDED, IMPLEMENTED BY YOU.
请注意,如果我要进行完全重写,它可能会像:
def get_input():
"""Get user input for the calculation"""
inputprompt = """Return the result of a calculation, based on user input.
Your input must be of the form X ? Y where X, Y are any number and ? is one of:
+, -, /, //, *, %
Please include spaces between operand and operator, or STOP to stop.
>> """
return input(inputprompt)
def calculate(operation):
"""Calculates the result based on which operator is used"""
import operator
operand_1, operator, operand_2 = operation
try:
operand_1, operand_2 = float(operand_1), float(operand_2)
except ValueError:
raise ValueError("Invalid operand")
try:
f = {"+": operator.add, "-": operator.sub,
"/": operator.truediv, "*": operator.mul,
"//": operator.floordiv, "%": operator.mod}[operator]
except KeyError:
raise ValueError("Invalid operator")
return f(operand_1, operand_2)
def main():
from collections import deque
history = deque()
# a deque is a list that allows easy popping and appending from left OR right
MAX_HISTORY_LENGTH = 10
while True
print("CALCULATOR:\n\n")
readable = get_input()
if "stop" in readable.lower():
break
operation = readable.split()
history.append(readable)
if len(history) > MAX_HISTORY_LENGTH:
history.popleft()
print("{} = {}".format(readable, calculate(operation))
input(" ( press ENTER to continue ) ")
main()
# we love functional programming!