+ 2

How to put a calculation in a variable

hello, I wanted to do a program, who ask two calculation with an unknown. But I met à big problem : I can't change the calculation into an int, because the input change it in a string, and can change, for exemple, '3*i+4' and '6*6' in int. Can you help me please ?

13th Jun 2018, 6:59 PM
Marc Betous
Marc Betous - avatar
10 ответов
+ 2
If your ‘i’ is the imaginary unit, look at math modules like numpy or sympy. If you want to input an expression (like in a calculator), you can make one yourself. (Or use sympy’s expressions and solve them for your variable.) If you choose to make your own calculator, here’s the idea: https://www.sololearn.com/learn/704/
13th Jun 2018, 8:18 PM
Pedro Demingos
Pedro Demingos - avatar
+ 5
ghali lawal I think you are exec() function is used for evaluation of the string in python. https://www.sololearn.com/learn/903/?ref=app
14th Jun 2018, 3:36 PM
Akash Pal
Akash Pal - avatar
+ 3
Just use type casting. input = int(input("Enter"))
13th Jun 2018, 7:03 PM
Akash Pal
Akash Pal - avatar
+ 2
Please show your code then.
13th Jun 2018, 7:06 PM
Akash Pal
Akash Pal - avatar
+ 2
why not use he eval method the start is just calculation = eval(input("Enter a calculation"))
13th Jun 2018, 10:37 PM
ghali lawal
ghali lawal - avatar
+ 1
yes but there is the problem : it doesn't work
13th Jun 2018, 7:05 PM
Marc Betous
Marc Betous - avatar
+ 1
the start is just calculation = int(input("Enter a calculation")) and it raise an error if I put a calculation : invalid interal for int() with base 10: '4+5*x'
13th Jun 2018, 7:14 PM
Marc Betous
Marc Betous - avatar
+ 1
ok thank you, I think it's the easiest way to do that :)
13th Jun 2018, 9:14 PM
Marc Betous
Marc Betous - avatar
+ 1
The input still a str, I can't eval it
14th Jun 2018, 3:33 PM
Marc Betous
Marc Betous - avatar
+ 1
thank you :D
14th Jun 2018, 3:37 PM
Marc Betous
Marc Betous - avatar