+ 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.
9 Respostas
+ 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
+ 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. 😁
+ 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
+ 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
+ 1
if python has an eval() function, try that instead of print
+ 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.')
+ 1
Eduardo, thanks! Will update my calc.
+ 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
0
try c = + if it accepts it