如何制作一个 python 计算器,它可以在两个以上的数字上加、减、乘、除、幂和模



我对Python很陌生,我想知道如何制作一个计算器,我可以在两个以上的数字上加,减,乘,除和其他运算符。如果你给我一个解释,我将不胜感激。我质疑是因为我想到了一种可怕且效率低下的方法,那就是为更多的运算符和更多的数字添加更多的 elif 标签

TL:DR (我猜( : 我想过制作一个用 Python 制作的计算器,它可以提供更多运算符和数字的选项(但我不知道如何制作一个更简单的计算器: 即:30 + 30 * 30。 67.874/20. 69 + 69 + 69 + 69 + 69 + 69. 30 ** (我认为这是一个幂运算符( 2. 等。 如果你不明白我想要什么,我可以帮你,你可以质疑我

这是我的普通计算器,没有输入两个以上的数字和一个运算符

def add(x, y):
return x + y

def subtract(x, y):
return x - y

def multiply(x, y):
return x * y

def divide(x, y):
return x / y

num1 = float(input("Enter a number :"))
op = input("Enter your selected operator :")
num2 = float(input("Enter another number :"))
if op == "+":
print(num1, "+", num2, "=", add(num1, num2))
elif op == "-":
print(num1, "-", num2, "=", subtract(num1, num2))
elif op == "*":
print(num1, "*", num2, "=", multiply(num1, num2))
elif op == "/":
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid input")

我知道这个评论/答案代码没有缩进,但是堆栈不允许我发布缩进,文件本身确实有缩进,所以idk

result = None
operand = None
operator = None
wait_for_number = True
while True:
if operator == '=':
print(f"Result: {result}")
break
elif wait_for_number == True:
while True:
try:
operand = float(input("Enter number: "))
except ValueError:
print("Oops! It is not a number. Try again.")
else:
if result == None:
result = operand
else:
if operator == '+':
result = result + operand
elif operator == '-':
result = result - operand
elif operator == '*':
result = result * operand
elif operator == '/':
result = result / operand
break
wait_for_number = False
else:
while True:
operator = input("Enter one of operators +, -, *, /, =: ")
if operator in ('+', '-', '*', '/', '='):
break
else:
print("Oops! It is not a valid operator. Try again.")
wait_for_number = True

你的问题还不够清楚,但如果我做对了,这应该可以。需要注意的重要提示:使用 eval(( 函数不是一个好的做法,因为如果输入不是来自你,它可能非常危险。以下是它的一些危险: https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

代码:

# the function takes an operator as a string like: “*” and multiple numbers thanks to the * (args) operator.
def calculate(operator, *numbers):

result = numbers[0]
#the for cycle goes through all numbers except the first
for number in range(1, len(numbers)):
#the eval() function makes it possible to python to interpret strings as a code part
result = eval(f"{result} {operator} {str(numbers[i])}")
print(result)

这是没有 eval(( 的代码。


import operator
# the function takes an operator as a string like: “*” and multiple numbers thanks to the * (args) operator.
def calculate(op, *numbers):
# binding each operator to its string counterpart
operators = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
result = numbers[0]
#the for cycle goes through all numbers except the first
for number in range(1, len(numbers)):
# carrying out the operation, using the dictionary above
result = operators[op](result, numbers[number])
print(result)

最新更新