Solving Linear Equations with SymPy (For Beginners)

By | February 13, 2026

SymPy allows you to easily solve linear equations as follows:

  1. Declare variables using the symbols() function.
  2. Describe the equation in SymPy (transform it so that zero is on the right side).
  3. Pass the equation and the variable to solve for to the solve() function.
  4. Display the return value of the solve() function.

2x+3=72x + 3 = 7

Defining the Equation and Declaring Variables

Describe the equation you want to solve in SymPy and declare the variables you will be using.

from sympy import symbols, solve

# Declare the variable x
x = symbols('x')

# Define the equation 2x + 3 = 7
equation = 2*x + 3 - 7

This code does the following:

  • from sympy import symbols, solve: Imports the symbols and solve functions from the SymPy library.
    • symbols('x'): Declares variable x as a SymPy symbol. This allows SymPy to treat x as a mathematical variable rather than just a string.
    • equation = 2*x + 3 - 7: Describes the equation 2x + 3 = 7 in SymPy. It’s expressed as 2x - 4 = 0 to have zero on the right side.
# Solve the equation
solution = solve(equation, x)

# Display the solution
print(solution)

This code does the following:

  • solution = solve(equation, x): Passes the equation you want to solve (equation) and the variable to solve for (x) to the solve() function. The solve() function returns the solutions to the equation as a list.
  • print(solution): Displays the solution.

This result indicates that the solution to the equation 2x + 3 = 7 is x = 2.

A More Complex Example

You can solve equations with fractions or negative numbers as coefficients and constants in a similar way.

from sympy import symbols, solve

# Declare the variable x
x = symbols('x')

# Define the equation -3/2 * x + 5 = 1/4
equation = (-3/2)*x + 5 - (1/4)

# Solve the equation
solution = solve(equation, x)

# Display the solution
print(solution)

# Output [3]