Python Code Runner

Write, run, and experiment with Python code directly in your browser. No installation required.

Python 3.12 (Pyodide)
Output Run your code to see output here.
Ready

✨ Features

What makes this code runner powerful

⚑ Instant Execution

Run Python code with one click. See output immediately, no server needed.

πŸ“š 30+ Sample Snippets

Explore common algorithms and patterns – from Fibonacci to decorators.

⌨️ Keyboard Shortcuts

Boost your workflow with Ctrl+Enter to run, Ctrl+Shift+C to clear, and more.

🧠 Async & Modern Python

Supports async/await, type hints, dataclasses, and all Python 3.12 features.

πŸ“¦ Standard Library Included

Use math, json, re, csv, collections, itertools, and many more.

🌐 100% Browser-Based

Powered by Pyodide (WebAssembly). No sign‑up, no installation, no data sent to servers.

πŸ“‹ Sample Snippets

Click any card to load the code into the editor, or use the β€œSamples” dropdown in the toolbar.

Hello World

print("Hello, World!")

Fibonacci Sequence

def fib(n): return n if n<=1 else fib(n-1)+fib(n-2)

List Operations

numbers = [1,2,3,4,5]   squares = [x**2 for x in numbers]

Dictionary

person = {"name": "Alice", "age": 30}   for k,v in person.items(): print(k,v)

Class Example

class Dog: def __init__(self, name): self.name = name

FizzBuzz

for i in range(1,21): print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i)

Async Example

import asyncio   async def say(): await asyncio.sleep(1); return "Done"

Decorator

@timer   def slow(): time.sleep(1)

Generator

def count_up(n): for i in range(n): yield i

Sort Algorithms

def quicksort(arr): ...

Prime Numbers

def is_prime(n): return n>1 and all(n%i for i in range(2,int(n**0.5)+1))

Palindrome Checker

def is_palindrome(s): return s == s[::-1]

CSV Parsing

import csv   reader = csv.DictReader(...)

JSON Handling

import json   data = json.loads('{"name":"Alice"}')

Recursion

def factorial(n): return 1 if n<=1 else n*factorial(n-1)

Lambda Functions

square = lambda x: x**2   list(map(lambda x: x**2, range(5)))

Filter & Map

filter(lambda x: x%2==0, range(10))   map(lambda x: x*2, range(5))

Set Operations

a = {1,2,3}   b = {3,4,5}   a.union(b), a.intersection(b)

Date & Time

from datetime import datetime   now = datetime.now()

Math Functions

import math   math.sqrt(16), math.pi, math.sin(0)

Binary & Hex

bin(10), hex(255)

Stack

class Stack: push(), pop(), peek()

Queue (deque)

from collections import deque   q.append(), q.popleft()

Binary Search Tree

insert(), inorder() traversal

Regex Matching

import re   re.findall(r"[\w.+-]+@[\w-]+", text)

Context Manager

class Timer: __enter__(), __exit__()

Dataclass

@dataclass   class Point: x: float; y: float

Counter

from collections import Counter   Counter(words)

Named Tuple

from collections import namedtuple

Matrix Multiply

def matrix_multiply(a, b): ...

Custom Exception

class InsufficientFundsError(Exception): pass

⌨️ Keyboard Shortcuts
Run code Ctrl+Enter
Clear output Ctrl+Shift+C
Load sample Ctrl+Shift+S
Focus editor Ctrl+Shift+E
πŸ’‘ Tips & Best Practices

Built-in modules – The runner includes the Python standard library. You can import math, random, datetime, json, csv, re, itertools, collections, and many others.

Async support – Use asyncio.run() to run async code. The runner supports async/await syntax.

Time limit – Long-running code (over 10 seconds) may be terminated to keep the page responsive.

No installation – Everything runs in your browser using Pyodide, a Python runtime compiled to WebAssembly.

PEP 8 – Write clean code following Python's style guide. Use 4 spaces for indentation, meaningful variable names, and keep lines under 79 characters.

Type Hints – Use type hints to make your code more readable and catch errors early: def greet(name: str) -> str:

Docstrings – Document your functions with docstrings: """This function does something."""

🐍 Python Built-in Functions

Essential built-in functions you can use in the runner:

print() – Output to console
len() – Get length of sequence
type() – Get type of object
int() – Convert to integer
float() – Convert to float
str() – Convert to string
list() – Convert to list
dict() – Create dictionary
set() – Create set
tuple() – Convert to tuple
sum() – Sum of iterable
max() – Maximum value
min() – Minimum value
sorted() – Sorted list
enumerate() – Index-value pairs
zip() – Zip iterables
any() – Check if any truthy
all() – Check if all truthy
filter() – Filter iterable
map() – Map function over iterable
range() – Generate sequence
input() – Read user input
isinstance() – Check type
issubclass() – Check subclass
abs() – Absolute value
round() – Round number
pow() – Power operation
divmod() – Quotient and remainder
open() – Open file
help() – Get help
dir() – List attributes
id() – Object identity
hash() – Hash value
bool() – Convert to boolean
bytes() – Create bytes
bytearray() – Create bytearray
memoryview() – Memory view
iter() – Get iterator
next() – Get next item
reversed() – Reverse iterable
🧩 Python Challenges

Try these coding challenges in the runner. Click the button to load the challenge code.

Challenge 1: Palindrome Checker

Write a function that checks if a string is a palindrome (reads the same forward and backward).

Challenge 2: Prime Number Generator

Generate all prime numbers up to a given limit using the Sieve of Eratosthenes.

Challenge 3: Word Frequency Counter

Count the frequency of each word in a given text using a dictionary.

Challenge 4: Fibonacci Iterator

Create a generator that yields Fibonacci numbers indefinitely.

Challenge 5: CSV to JSON Converter

Convert CSV data to JSON format using Python's csv and json modules.

🚨 Common Python Errors & Solutions

SyntaxError: invalid syntax

Check for missing parentheses, colons, or incorrect indentation. Python is very strict about syntax.

print("Hello" # Missing closing parenthesis

NameError: name 'x' is not defined

You're trying to use a variable that hasn't been assigned a value yet.

print(x) # x was never defined

TypeError: can only concatenate str (not "int") to str

You're trying to combine different data types without converting them.

print("Age: " + 25) # Should be: print("Age: " + str(25))

IndexError: list index out of range

You're accessing an index that doesn't exist in the list.

items = [1, 2, 3]; print(items[5])

KeyError: 'key'

You're trying to access a dictionary key that doesn't exist.

d = {"name": "Alice"}; print(d["age"]) # Use d.get("age", "default")

ValueError: invalid literal for int()

You're trying to convert a non-numeric string to an integer.

int("abc") # Use try/except to handle this

ZeroDivisionError: division by zero

You're trying to divide a number by zero.

10 / 0 # Check the denominator before dividing

FileNotFoundError: [Errno 2] No such file or directory

You're trying to open a file that doesn't exist.

open("nonexistent.txt") # Use try/except to handle this

IndentationError: expected an indented block

Python uses indentation to define code blocks. Make sure you indent consistently.

def hello():\nprint("Hello") # Indent the print statement

ImportError: No module named 'xyz'

You're trying to import a module that doesn't exist or isn't installed.

import non_existent_module # Check the module name

πŸ“š Python Standard Library Modules

Useful modules you can import and use in the runner:

math – Mathematical functions
random – Generate random numbers
datetime – Date and time handling
json – JSON encoding/decoding
csv – CSV file reading/writing
re – Regular expressions
itertools – Iterator tools
collections – Specialized containers
functools – Higher-order functions
os – Operating system interface
sys – System-specific parameters
time – Time-related functions
pathlib – Path manipulation
argparse – Command-line parsing
logging – Logging framework
hashlib – Cryptographic hashing
The code runner is powered by Pyodide. The first run may take a few seconds to load the Python runtime.