Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Pennylane

Learn Pennylane - 10 Code Examples & CST Typing Practice Test

PennyLane is an open-source Python library for differentiable programming of quantum computers. It enables hybrid quantum-classical machine learning workflows, automatic differentiation, and optimization across multiple quantum hardware platforms.

View all 10 Pennylane code examples →
PennyLane Simple Quantum CircuitPennyLane Bell State CircuitPennyLane GHZ State CircuitPennyLane Quantum TeleportationPennyLane Variational Circuit ExamplePennyLane Controlled Phase GatePennyLane Swap TestPennyLane Gradient ComputationPennyLane Quantum Fourier TransformPennyLane Quantum Circuit with Measurement

Learn PENNYLANE with Real Code Examples

Updated Nov 25, 2025

Explain

PennyLane allows developers to build quantum circuits that are compatible with classical ML frameworks like PyTorch and TensorFlow.

It supports variational quantum algorithms, quantum neural networks, and hybrid quantum-classical models.

PennyLane provides a unified interface to simulate circuits or run them on hardware from multiple providers, including Rigetti, IBM, Google, and Amazon Braket.

Core Features

Quantum nodes (QNodes) for circuit representation

Tape-based differentiation to compute gradients

Device abstraction layer for different quantum backends

Interfaces with PyTorch, TensorFlow, JAX for hybrid models

Support for photonic, superconducting, and trapped-ion hardware via plugins

Basic Concepts Overview

Qubit: quantum bit used in circuits

QNode: quantum node representing a quantum function

Device: backend for executing QNodes (simulator or hardware)

Tape: internal data structure used for gradient computation

Interface: classical ML framework integrated with PennyLane

Project Structure

circuits/ - quantum circuit definitions as Python functions

models/ - hybrid quantum-classical models

notebooks/ - experimentation and visualization

data/ - results and measurement outcomes

tests/ - unit tests for circuits and models

Building Workflow

Define a quantum function representing a circuit

Wrap it in a QNode specifying a device and interface

Compute gradients using automatic differentiation

Combine with classical models or optimizers

Execute on a simulator or hardware backend

Difficulty Use Cases

Beginner: simulate small quantum circuits with default qubit devices

Intermediate: build hybrid models with automatic differentiation

Advanced: run variational algorithms on hardware backends

Expert: integrate PennyLane with large ML pipelines and optimization workflows

Enterprise: deploy hybrid quantum-classical solutions across multiple hardware platforms

Comparisons

PennyLane vs Qiskit: PennyLane focuses on differentiable programming and hybrid ML; Qiskit is more general for quantum circuit design and algorithms

PennyLane vs Cirq: PennyLane provides ML interfaces and automatic differentiation; Cirq is more low-level for Google hardware

PennyLane vs Forest: PennyLane is hardware-agnostic and ML-first; Forest focuses on Rigetti hardware with pyQuil

PennyLane vs Braket: PennyLane allows hybrid differentiable programming; Braket provides multi-vendor cloud hardware access

PennyLane vs TensorFlow Quantum: Both focus on ML integration, PennyLane supports more backends and hardware plugins

Versioning Timeline

Initial release by Xanadu - PennyLane as differentiable quantum programming framework

Integration with TensorFlow, PyTorch, and JAX interfaces

Plugin system introduced to support multiple hardware backends

Enhanced gradient computation and hybrid model examples

Ongoing improvements, expanded device plugins, and community contributions

Glossary

QNode: Quantum node representing a circuit and measurement

Device: Backend for executing circuits (simulator or hardware)

Tape: Internal data structure used for automatic differentiation

Interface: Classical ML framework integrated with PennyLane

Plugin: Backend-specific adapter to connect PennyLane to quantum hardware

Installation Setup

Install Python 3.7+

Install PennyLane via `pip install pennylane`

Install optional plugins for hardware access (e.g., `pennylane-qiskit`, `pennylane-rigetti`)

Install classical ML frameworks if using hybrid models (TensorFlow, PyTorch, JAX)

Verify installation with a small QNode example

Environment Setup

Install Python 3.7+ and PennyLane

Install optional device plugins

Install classical ML frameworks (PyTorch, TensorFlow, JAX)

Verify installation by running example QNode circuits

Set up cloud API credentials if using hardware backends

Config Files

requirements.txt - dependencies

notebooks/ - example circuits and models

scripts/ - hybrid training scripts

data/ - measurement and training logs

plugin configuration files (if accessing hardware backends)

Cli Commands

Run Python scripts: `python script.py`

Install plugins: `pip install pennylane-qiskit`

Launch Jupyter notebooks for experimentation

Monitor results and training with TensorBoard or matplotlib

Use optimizer CLI from classical ML frameworks

Internationalization

Global developer and research community

Documentation primarily in English

Support for multi-cloud quantum hardware

Open-source contributions from worldwide researchers

Use in international academic and industry projects

Accessibility

Python-based - accessible to a wide developer community

Open-source under Apache 2.0 license

Device-agnostic and compatible with multiple quantum backends

Integrates with popular ML frameworks

Extensive tutorials and documentation for beginners and researchers

Ui Styling

Jupyter notebooks for interactive experimentation

Python scripts for production workflows

Matplotlib, seaborn, or TensorBoard for visualization

Logging dashboards for measurement and training results

CLI tools from classical ML frameworks

State Management

Track versions of circuits and QNode definitions

Store measurement outcomes and training checkpoints

Maintain reproducible experiments with fixed seeds

Track classical optimizer states for hybrid models

Log hardware execution parameters and results

Data Management

Serialize measurement outcomes for later analysis

Maintain classical ML model checkpoints

Archive QNode definitions and circuit parameters

Document experiment metadata and results

Use notebooks or scripts for reproducible workflows

Architecture

QNode - quantum node representing a circuit and measurement

Devices - quantum backends (simulators or hardware)

Interfaces - bridges to classical ML frameworks

Tapes - internal representation for automatic differentiation

Plugins - connect PennyLane to multiple quantum hardware providers

Rendering Model

Python function defining circuit -> QNode -> device execution -> classical optimization

Gradient computation embedded in circuit execution

Support for multiple hardware backends via plugins

Integration with classical ML frameworks for optimization loops

Visualization and analysis of measurement outcomes

Architectural Patterns

Separation of concerns: circuit definition, execution, differentiation

Device abstraction for hardware-agnostic execution

Tape-based representation for gradient computation

Plugin architecture for backend extensibility

Hybrid optimization loops with classical-quantum integration

Real World Architectures

Hybrid quantum-classical ML pipelines (PennyLane + PyTorch/TensorFlow)

Variational quantum algorithms for chemistry (VQE, QAOA)

Quantum neural networks for classification or regression

Optimization workflows combining quantum circuits and classical optimizers

Research experiments across multiple quantum hardware platforms

Design Principles

Hardware-agnostic design for quantum circuits

Seamless integration with classical ML frameworks

Automatic differentiation for parameterized circuits

Open-source and community-driven development

Focus on hybrid quantum-classical applications

Scalability Guide

Use default.qubit for local simulation

Scale hybrid models by batching gradients

Parallelize circuit evaluations across classical resources

Use cloud hardware selectively for critical experiments

Monitor and optimize resource usage in large-scale training loops

Migration Guide

Update PennyLane via pip regularly

Update device plugins for new backend versions

Check for breaking changes in QNode or device APIs

Ensure classical ML frameworks are compatible with PennyLane version

Document experiment reproducibility when upgrading

Performance Notes

Simulator performance decreases exponentially with qubit number

Hardware execution may have latency and noise

Gradient computation can be parallelized using classical ML frameworks

Parameter-shift method provides exact gradients for many gates

Hybrid optimization loops benefit from batch processing

Security Notes

Keep hardware API tokens secure

Avoid transmitting sensitive data over insecure networks

Log experiment configurations for reproducibility

Validate classical-quantum data pipelines

Use secure storage for measurement results

Monitoring Analytics

Track training loss and gradient magnitudes

Monitor measurement statistics

Analyze hardware execution results

Log optimizer states for reproducibility

Visualize performance metrics in notebooks or dashboards

Code Quality

Write modular QNode functions

Document circuit parameters and measurements

Use version control for scripts and notebooks

Simulate before deploying to hardware

Validate gradients and optimizer behavior

Practical Examples

Compute expectation value of Pauli operators

Train a quantum neural network using PyTorch interface

Run a VQE algorithm on a Qiskit or Rigetti backend

Simulate QAOA for combinatorial optimization problems

Perform gradient-based optimization of a parameterized circuit

Troubleshooting

Ensure device plugins are installed for hardware access

Check compatibility between PennyLane and classical ML frameworks

Validate QNode circuits for correct gate usage

Monitor gradient computation for numerical issues

Use small circuits first before scaling up

Testing Guide

Simulate small circuits with built-in devices

Validate gradients against finite-difference approximations

Test hybrid model training loops on simulated backend

Check hardware execution with short circuits

Log intermediate results for debugging

Deployment Options

Simulate circuits locally with default devices

Run circuits on cloud hardware via plugins

Combine with classical ML models for hybrid training

Deploy trained models for inference

Automate experiments via notebooks or scripts

Tools Ecosystem

PennyLane core library - quantum circuit definition and differentiation

Device plugins - Qiskit, Forest, Cirq, Braket, etc.

Classical ML frameworks - PyTorch, TensorFlow, JAX

Optimization libraries - SciPy, PyTorch optimizers

Visualization tools - matplotlib, seaborn, TensorBoard

Integrations

Qiskit, Cirq, Rigetti Forest, Amazon Braket via PennyLane plugins

TensorFlow, PyTorch, JAX interfaces for hybrid models

Classical optimization and machine learning pipelines

Jupyter notebooks for experimentation

Quantum chemistry libraries for VQE simulations

Productivity Tips

Prototype circuits on simulators first

Leverage automatic differentiation for fast optimization

Use plugins to switch backends easily

Batch parameterized circuit evaluations

Combine classical ML tools for rapid hybrid model iteration

Challenges

Managing gradients and differentiable programming across devices

Dealing with noisy hardware backends

Integrating classical ML optimizers with quantum circuits

Scaling hybrid models with many parameters

Ensuring reproducibility across backends

Learning Path

Learn Python and basic quantum computing concepts

Study PennyLane QNode and device concepts

Practice building and simulating small circuits

Integrate with PyTorch, TensorFlow, or JAX

Train simple hybrid quantum-classical models

Skill Improvement Plan

Week 1: Install PennyLane and run example QNode simulations

Week 2: Explore QNode differentiation and parameter-shift gradients

Week 3: Build simple hybrid models with PyTorch or TensorFlow

Week 4: Run variational algorithms on simulators or cloud hardware

Week 5: Benchmark models, visualize results, and optimize workflows

Interview Questions

What is PennyLane and what are its primary features?

Explain how QNodes and devices work in PennyLane.

How does PennyLane integrate with classical ML frameworks?

Describe a hybrid quantum-classical model workflow using PennyLane.

What is the role of automatic differentiation in PennyLane?

Cheat Sheet

QNode = `@qml.qnode(dev)` decorated function

`qml.device('default.qubit', wires=2)` = simulator backend

`qml.expval(qml.PauliZ(0))` = measure expectation value

Use classical optimizers from PyTorch/TensorFlow for hybrid training

`qml.gradients.param_shift` = compute gradients of QNode

Books

Quantum Machine Learning with PennyLane

Hybrid Quantum-Classical Algorithm textbooks

Research papers and notebooks from Xanadu

Quantum computing for ML practitioners

Differentiable programming in quantum computing

Tutorials

QNode and device tutorials

Hybrid ML workflow examples with PyTorch and TensorFlow

Variational algorithm tutorials (VQE, QAOA)

Hardware plugin tutorials (Qiskit, Forest, Braket)

Gradient computation and optimization guides

Official Docs

https://pennylane.ai/ (official documentation)

https://pennylane.ai/qml/ (quantum ML tutorials and guides)

Community Links

PennyLane GitHub

Xanadu forums and Slack

Quantum StackExchange

Official example notebooks

Research publications using PennyLane

Community Support

PennyLane GitHub repositories

Xanadu forums and Slack community

Quantum StackExchange for PennyLane questions

Official tutorials and example notebooks

Research papers and hybrid algorithm publications

Monetization

Quantum ML consulting

Hybrid algorithm development for research and industry

Teaching and workshops on quantum machine learning

Cloud-based hybrid model prototyping

Benchmarking hybrid quantum-classical workflows

Future Roadmap

Expanded device plugin support

Improved gradient methods and differentiation techniques

More hybrid ML model examples and tutorials

Enhanced integration with classical ML frameworks

Community-driven feature additions and research contributions

When Not To Use

If you need only low-level quantum gate control

For non-hybrid quantum algorithms not involving ML

When working solely with a single hardware provider without ML integration

For very large-scale simulation beyond classical resources

If automatic differentiation is not required

Final Summary

PennyLane is a versatile library for hybrid quantum-classical machine learning and differentiable quantum programming.

It abstracts quantum hardware through devices and QNodes, supports automatic differentiation, and integrates with major ML frameworks.

Ideal for research, prototyping variational algorithms, and training hybrid models on multiple simulators and hardware backends.

It bridges classical and quantum computing, enabling gradient-based optimization and ML applications.

Faq

Is PennyLane free to use?

Yes, it is open-source under Apache 2.0 license.

Which hardware does PennyLane support?

Supports multiple providers via plugins: Qiskit, Cirq, Forest, Braket, Rigetti, etc.

Can I compute gradients automatically?

Yes - PennyLane supports automatic differentiation using parameter-shift or finite-difference methods.

Does PennyLane support hybrid ML workflows?

Yes - integrates seamlessly with PyTorch, TensorFlow, and JAX.

How do I simulate circuits locally?

Use built-in devices like `default.qubit` or `default.mixed`.

Code Sample Descriptions

1

PennyLane Simple Quantum Circuit

import pennylane as qml
from pennylane import numpy as np

# Define a 2-qubit device
dev = qml.device('default.qubit', wires=2)

# Define a quantum circuit
@qml.qnode(dev)
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=1)
    qml.CNOT(wires=[0,1])
    return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))

# Evaluate the circuit
params = np.array([0.1, 0.2])
print(circuit(params))

A minimal PennyLane example defining a 2-qubit quantum circuit, applying gates, and computing expectation values.

Let’s Try →
2

PennyLane Bell State Circuit

import pennylane as qml

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev)
def bell_state():
    hadamard(0)
    qml.CNOT(wires=[0,1])
    return qml.state()

print(bell_state())

Creates a Bell state using a Hadamard and CNOT gate.

Let’s Try →
3

PennyLane GHZ State Circuit

import pennylane as qml

dev = qml.device('default.qubit', wires=3)

@qml.qnode(dev)
def ghz_state():
    qml.Hadamard(wires=0)
    qml.CNOT(wires=[0,1])
    qml.CNOT(wires=[0,2])
    return qml.state()

print(ghz_state())

Generates a 3-qubit GHZ state.

Let’s Try →
4

PennyLane Quantum Teleportation

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=3)

@qml.qnode(dev)
def teleport(msg_state):
    qml.QubitStateVector(msg_state, wires=0)
    qml.Hadamard(wires=1)
    qml.CNOT(wires=[1,2])
    qml.CNOT(wires=[0,1])
    qml.Hadamard(wires=0)
    return qml.state()

msg_state = [1,0]
print(teleport(msg_state))

Implements the quantum teleportation protocol.

Let’s Try →
5

PennyLane Variational Circuit Example

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev)
def var_circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=1)
    qml.CNOT(wires=[0,1])
    return qml.expval(qml.PauliZ(0))

params = np.array([0.5, 0.3])
print(var_circuit(params))

A simple variational quantum circuit using RX and RY rotations.

Let’s Try →
6

PennyLane Controlled Phase Gate

import pennylane as qml

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev)
def cphase_example():
    qml.Hadamard(wires=0)
    qml.CPhase(np.pi/2, wires=[0,1])
    return qml.state()

print(cphase_example())

Applies a controlled phase rotation between two qubits.

Let’s Try →
7

PennyLane Swap Test

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=3)

@qml.qnode(dev)
def swap_test(state1, state2):
    qml.Hadamard(wires=0)
    qml.QubitStateVector(state1, wires=1)
    qml.QubitStateVector(state2, wires=2)
    qml.CSWAP(wires=[0,1,2])
    qml.Hadamard(wires=0)
    return qml.expval(qml.PauliZ(0))

state1 = [1,0]
state2 = [0,1]
print(swap_test(state1, state2))

Performs a swap test to compute the overlap of two quantum states.

Let’s Try →
8

PennyLane Gradient Computation

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=1)

@qml.qnode(dev)
def circuit(x):
    qml.RX(x, wires=0)
    return qml.expval(qml.PauliZ(0))

x = 0.5
grad_fn = qml.grad(circuit)
print(grad_fn(x))

Computes the gradient of a simple variational circuit.

Let’s Try →
9

PennyLane Quantum Fourier Transform

import pennylane as qml
import numpy as np

dev = qml.device('default.qubit', wires=3)

def qft3():
    qml.Hadamard(wires=0)
    qml.CPhase(np.pi/2, wires=[0,1])
    qml.CPhase(np.pi/4, wires=[0,2])
    qml.Hadamard(wires=1)
    qml.CPhase(np.pi/2, wires=[1,2])
    qml.Hadamard(wires=2)

@qml.qnode(dev)
def qft_circuit():
    qft3()
    return qml.state()

print(qft_circuit())

Implements a simple 3-qubit quantum Fourier transform.

Let’s Try →
10

PennyLane Quantum Circuit with Measurement

import pennylane as qml

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev)
def measure_circuit():
    qml.Hadamard(wires=0)
    qml.CNOT(wires=[0,1])
    return qml.sample()

print(measure_circuit())

Applies gates and measures qubits in the computational basis.

Let’s Try →

Frequently Asked Questions about Pennylane

What is Pennylane?

PennyLane is an open-source Python library for differentiable programming of quantum computers. It enables hybrid quantum-classical machine learning workflows, automatic differentiation, and optimization across multiple quantum hardware platforms.

What are the primary use cases for Pennylane?

Developing hybrid quantum-classical machine learning models. Simulating quantum circuits and computing gradients with automatic differentiation. Running variational algorithms such as VQE and QAOA. Integrating with classical ML frameworks like TensorFlow, PyTorch, and JAX. Executing quantum programs on hardware from multiple vendors

What are the strengths of Pennylane?

Seamless integration with classical ML frameworks. Automatic differentiation for hybrid quantum-classical models. Flexible device-agnostic design for multiple quantum backends. Active community and strong documentation. Rapid prototyping for research and experimentation

What are the limitations of Pennylane?

Simulation of large circuits is computationally intensive. Performance depends on the backend and hardware availability. Requires familiarity with quantum computing and ML frameworks. Less low-level control compared to SDKs like Qiskit or Forest. Certain advanced features may require multiple plugins

How can I practice Pennylane typing speed?

CodeSpeedTest offers 10+ real Pennylane code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.