Python Code Runner
Write, run, and experiment with Python code directly in your browser. No installation required.
π Quick Navigation
Jump to any section instantly
β¨ 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.
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
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."""
Essential built-in functions you can use in the runner:
print() β Output to consolelen() β Get length of sequencetype() β Get type of objectint() β Convert to integerfloat() β Convert to floatstr() β Convert to stringlist() β Convert to listdict() β Create dictionaryset() β Create settuple() β Convert to tuplesum() β Sum of iterablemax() β Maximum valuemin() β Minimum valuesorted() β Sorted listenumerate() β Index-value pairszip() β Zip iterablesany() β Check if any truthyall() β Check if all truthyfilter() β Filter iterablemap() β Map function over iterablerange() β Generate sequenceinput() β Read user inputisinstance() β Check typeissubclass() β Check subclassabs() β Absolute valueround() β Round numberpow() β Power operationdivmod() β Quotient and remainderopen() β Open filehelp() β Get helpdir() β List attributesid() β Object identityhash() β Hash valuebool() β Convert to booleanbytes() β Create bytesbytearray() β Create bytearraymemoryview() β Memory viewiter() β Get iteratornext() β Get next itemreversed() β Reverse iterableTry 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.
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
Useful modules you can import and use in the runner:
math β Mathematical functionsrandom β Generate random numbersdatetime β Date and time handlingjson β JSON encoding/decodingcsv β CSV file reading/writingre β Regular expressionsitertools β Iterator toolscollections β Specialized containersfunctools β Higher-order functionsos β Operating system interfacesys β System-specific parameterstime β Time-related functionspathlib β Path manipulationargparse β Command-line parsinglogging β Logging frameworkhashlib β Cryptographic hashingπ¬ Python, weekly
Short lessons, real code, and ecosystem news β every week