Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Very simple equations in python

Hi, so i'm pretty new to programming but I understand and can use the basic "things" in python and js (loops of different types, functions, that sort of thing) and I've been wanting to write a program in python where it gets input and asks for an equation i.e. x + 6 = 12, then solves it and prints x = 6. So Im stuck on how to do the solving part. Please help!

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Hoo boy. Alright, I can't get a full answer for every situation, but here's my quick answer to it.

Basically you're looking at a few parts to this software.

  • It has to take input.
  • It has to break that input apart into logical parts. In this case, a value, an operation, another value, an equals sign, and an answer.
  • Then it has to turn the values that are numbers into numbers.
  • Then it has to know how to reverse the operation. In this case, turn + into -.
  • Then it has to swap the operator around and put the answer in the place of the unknown value.
  • Finally, it has to evaluate the new equation and give back the answer.

None of these steps are hard (check out the ast module's literal_eval for the last step) but that's for a super simple solution. Anything more complicated will take a lot more time.

Or you could use the sympy library. I just filmed a course on installing 3rd-party libraries but it's unfortunately not out yet (probably a month away).

Wow thanks Kenneth! That's exactly what I've been looking for!