Why the fault is :invalid literal for int () with base 10 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why the fault is :invalid literal for int () with base 10

print(int("3*(6+4)")+int("2+(4/5)"))

17th Sep 2017, 3:19 AM
Otes Urop
Otes Urop - avatar
3 Answers
+ 7
You are trying to parse "3*(6+4)" as an integer. This is actually a string literal which contains chars such as *, (, +, and hence makes the literal invalid to be parsed to integer of base 10. You might be trying to do: print(eval("3*(6+4)")+eval("2+(4/5)"))
17th Sep 2017, 3:53 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
You can't evaluate the expression with int() because you are trying to convert operators to integers - i.e. while int("6") is 6, int("6 + 4") is not 10. You can either convert each string number to an integer and then do the math, e.g. print(int("3") * (int("6") + int("4")) + int("2") + int("4") / int("5")) or, you can use eval() to evaluate the string expressions, i.e. like this: print(eval("3*(6+4)")+eval("2+(4/5)")) Just a word of caution - eval() can open the door to malicious code in some circumstances - see, e.g.: http://www.geeksforgeeks.org/eval-in-JUMP_LINK__&&__python__&&__JUMP_LINK/ but it does make a fun one-line calculator: print(eval(input()))
17th Sep 2017, 3:54 AM
David Ashton
David Ashton - avatar
+ 1
Thank you two
17th Sep 2017, 4:00 AM
Otes Urop
Otes Urop - avatar