I want to check operator and result print only as number, not in brackets. But I do not know how to add it in my code. Ideally check numbers as float.
texts = ["give first number: ",
"give operator: ", "give second number: "]
allowed_operators = ['+', '-', '/', '*', '**', '%']
def calculate(value_list):
#[ 1, "+", 1]
num1, operator, num2 = value_list
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '**':
return num1 ** num2
elif operator == '/':
return num1 / num2
elif operator == '%':
return num1 % num2
last_result = None
while True:
values = []
i = 0
while i < 3:
value = input("give value: ")
if value == "q":
exit(0)
if value in allowed_operators:
values.append(value) # [+]
else:
values.append(float(value))
if value in allowed_operators and i == 0:
if last_result == None:
print("Last calculation does not exist. ")
continue
else:
values.insert(0, last_result)
i += 1
i += 1
print(values)
result = calculate(values)
print(f'Result: {result}')
last_result = result
jonrsharpe
123k31 gold badges278 silver badges489 bronze badges
-
Does this answer your question? Basic Python calculatorjuagicre– juagicre2022年04月05日 14:28:00 +00:00Commented Apr 5, 2022 at 14:28
2 Answers 2
Not sure if I understand your problem correctly, but if you want to print the intermediate calculation without brackets then change
print(values)
to
print(" ".join(str(value) for value in values))
Sign up to request clarification or add additional context in comments.
Comments
Not sure what you need, but the calculation function can use operator module:
import operator
def calculate(value_list):
# [ 1, "+", 1]
num1, flag, num2 = value_list
flag_func = {'+': 'add', '-': 'sub', '*': 'mul', '**': 'pow', '/': 'truediv', '%': 'mod'}
if func := flag_func.get(flag):
return getattr(operator, func)(num1, num2)
raise Exception(f'Invalid operate {flag=}')
answered Apr 4, 2022 at 13:11
Waket Zheng
6,5792 gold badges23 silver badges38 bronze badges
Comments
lang-py