+ 1

Python symbol +

Hi. Need good advice. Is it possible to use symbols like '+' as varible for arethmetical operations? Example: a = 1 b = 2 c = '+' So d = a, c, b to perform 1+2=3. I get print (a,c,b) like 1+2 without result.

14th Aug 2018, 8:49 PM
Alex
Alex - avatar
9 ответов
+ 6
This works: a = '1' b = '2' c = '+' d = eval(a + c + b) print(d) # the eval function executes a string as if it is a line of code
14th Aug 2018, 9:25 PM
Eduardo Petry
Eduardo Petry - avatar
+ 5
alex Nice code! You don't need those print statements when asking for input, you can do: a = input("Input the first number: ") (...) b = input("Choose operation: + - * / : ") (...) c = input("Input the second number: ") Also, instead of showing "Error. Try again." if the input operator is invalid, you can print something like "Invalid operator. Try again." for clearer code. 😁
15th Aug 2018, 2:21 PM
Eduardo Petry
Eduardo Petry - avatar
+ 2
You are mistaking a symbol for an operator. '+' is the symbol and + is the operator. 1 + 2 = 3 1 '+' 2 has no meaning but, it's just 2 numbers and a symbol. You could use eval() on a string: eval('1 + 2') will give 3 as the answer. print(1,'+',2) wil just print 3 things in a row: 1 + 2
14th Aug 2018, 9:22 PM
davy hermans
davy hermans - avatar
+ 2
Mates, thank yor for help! Here's some new iteration: ========= print('Enter any mathematical task, e.g: 100 * 100, 85 % 37, 8^2 or 97 // 84.') while 1: try: print(eval(input('Input: '))) except Exception as err: print('Wrong input, please re-enter.\n') continue
20th Aug 2018, 3:18 PM
Alex
Alex - avatar
+ 1
if python has an eval() function, try that instead of print
14th Aug 2018, 8:58 PM
ReimarPB
ReimarPB - avatar
+ 1
Mates, thanks a lot! here's the final code: print('Hey, the calc is ready. \n') while True: print('Input the first number: ') a = input() print('Choose operation: + - * / : ') b = input() if b in ['+','-','*','/']: print("Input the second number: ") c = input() if c == '0' and b == '/': print('Error, division by zero.') else: d = eval(a + b + c) print('Result: ', d) else: print('Error. Try again.')
15th Aug 2018, 8:53 AM
Alex
Alex - avatar
+ 1
Eduardo, thanks! Will update my calc.
15th Aug 2018, 2:58 PM
Alex
Alex - avatar
+ 1
and finally: user can input anything)) print('Enter any mathematical task, e.g: 100 * 100, 85 % 37, 8^2 or 97 // 84.') while 1: try: print(eval(input('Input: ')),'\n') except Exception as err: print('Wrong input, please re-enter.\n') continue
20th Aug 2018, 4:24 PM
Alex
Alex - avatar
0
try c = + if it accepts it
14th Aug 2018, 8:55 PM
Mohmmad Gaith Alhilwany
Mohmmad Gaith Alhilwany - avatar