---
title: Example usage of the Python SDK
slug: feature-experimentation/docs/example-usage-python
docTags: 
createdAt: 2026-08-05T20:39:59.000Z
---

After installing the Python SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.

This example walks through the following three key steps:

1. Evaluate a flag with the key `product_sort` using the `decide` method. This also sends a decision event to Optimizely to record that the user was exposed to the experiment.
2. Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
   - Check the flag's enabled state and read a configuration variable (`sort_method`) to determine which experience the user gets.
   - Check the flag variation directly and run the corresponding control or treatment code.
3. Track a conversion event called `purchased` to measure the experiment's impact. The `track_event` method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your [Experiment Results page](docId:_K6n7h_MZ8b0xn6yWPrrq).

```python
from optimizely import optimizely

# Instantiate an Optimizely client
optimizely_client = optimizely.Optimizely(sdk_key = "<Your_SDK_Key>")

# create a user and decide a flag rule (such as an A/B test) for them
user = optimizely_client.create_user_context("user123", {"logged_in": True})
decision = user.decide("product_sort")

# did the decision fail with a critical error?
try:
  variation_key = decision.variation_key
except:
  print("decision error: {}".format(decision.reasons))

# execute code based on flag enabled state
enabled = decision.enabled
        
if enabled:
  # get flag variable values
  sort_method = decision.variables["sort_method"]

# or execute code based on flag variation
if variation_key == 'control':
    pass
    # Execute code for variation A
elif variation_key == 'treatment':
    pass
    # Execute code for variation B
else:
    pass
    # Execute code for users who don't qualify for the experiment

# Track a user event        
user.track_event("purchased")
```
