What you’ll build
You’ll create a simple Python script that uses Z3 to solve a system of constraints. The solver will find values for variables that satisfy all constraints simultaneously.Install Z3
The easiest way to get started is to install Z3 via a package manager. Choose your preferred language:
- Python
- JavaScript/TypeScript
- .NET
- Java
Install the Python bindings using pip:This installs both the Z3 library and Python bindings.
Write your first Z3 program
Create a file called This program:
first_solve.py with the following code:first_solve.py
- Creates two real-valued variables
xandy - Adds constraints that define valid values
- Checks if the constraints can be satisfied
- Prints a model showing values that satisfy all constraints
Run the program
Execute your script:You should see output like:
The output
sat means the constraints are satisfiable. The model shows one possible solution: x = 4 and y = 2. Note that 4 + 2 > 5, 4 > 1, and 2 > 1, so all constraints are satisfied.Experiment with unsatisfiable constraints
Try adding a conflicting constraint to see what happens when no solution exists:This will output:The solver correctly identifies that no values can satisfy both
x + y > 5 and x + y < 3 simultaneously.Understanding the results
Z3 returns one of three results:sat
Constraints are satisfiable. A model (solution) is available.
unsat
No solution exists. The constraints are contradictory.
unknown
The solver couldn’t determine satisfiability (usually due to timeouts or resource limits).
Common patterns
Here are some patterns you’ll use frequently:Declaring variables
Adding constraints
Checking and retrieving models
Next steps
Now that you’ve solved your first problems with Z3, explore these resources:Core concepts
Learn about SMT solving, expressions, and solvers
Python API
Comprehensive guide to the Python bindings
Examples
Browse practical examples and tutorials
Optimization
Learn how to optimize objectives with Z3
