0

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
asked Apr 4, 2022 at 12:36
1

2 Answers 2

0

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))
answered Apr 4, 2022 at 13:04
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.