Write, run, and test Python code directly in your browser without installation. The perfect online Python compiler for learning, testing, and quick code verification.
print("Hello, world!")
# Try writing your Python code here
name = input("Enter your name: ")
print(f"Hello, {name}!")
# The execution result will appear here
Python Online Compiler Features
Instant Execution
Run Python code instantly for free without installing an interpreter or configuring your environment.
Mobile Friendly
Write and test Python code on any device - from desktop computers to smartphones.
Save Your Code
Save your solutions for future work and share them with other developers.
Detailed Error Messages
Get precise error descriptions and output after each code execution for quick troubleshooting and debugging.
Code Autocompletion
Speed up your coding with smart autocompletion — fewer errors and more time to focus on solving problems.
Customizable Interface
Personalize your editor by choosing dark or light theme for a more comfortable coding experience. The interface is fully available in English.
Syntax Guide
# Variables and data types in Python
# In Python, you don't need to explicitly specify variable types
name = "Alex" # string
age = 30 # integer
height = 1.75 # float
is_python_fun = True # boolean
# Variables can be used in strings with f-strings
print(f"My name is {name}, I'm {age} years old. My height is {height} m.")
print(f"Is learning Python fun? {is_python_fun}")
# Example of using different data types
print("Data type of name:", type(name))
print("Data type of age:", type(age))
print("Data type of is_python_fun:", type(is_python_fun))
# Complex data types
numbers = [1, 2, 3, 4, 5] # list
user_info = { # dictionary
"name": "Alex",
"age": 30,
"languages": ["Python", "JavaScript", "SQL"]
}
coordinates = (55.7522, 37.6156) # tuple (immutable)
unique_tags = {"python", "programming", "learning"} # set
# Type conversion
str_number = "42"
int_number = int(str_number) # converting string to integer
print(f"Converted number: {int_number}, type: {type(int_number)}")
# Operations with numbers
a, b = 10, 3
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b}")
print(f"Integer division: {a // b}")
print(f"Modulo: {a % b}")
print(f"Exponentiation: {a ** b}")
# Conditionals and loops in Python
# Conditional statements
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x equals 5")
else:
print("x is less than 5")
# Logical operators
a, b = 5, 10
if a > 0 and b > 0:
print("Both numbers are positive")
if a > 0 or b < 0:
print("At least one number is positive")
if not (a > b):
print("a is not greater than b")
# Ternary operator
age = 20
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}")
# Loops: for and while
# Example with for loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"Fruit: {fruit}")
# For loop with range() function
for i in range(1, 5): # from 1 to 4
print(f"Number: {i}")
# For loop with enumerate() to get index
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# Example with while loop
count = 1
while count <= 3:
print(f"Iteration {count}")
count += 1
# Loop control: break and continue
for i in range(10):
if i == 3:
continue # skip iteration if i equals 3
if i == 7:
break # exit loop if i equals 7
print(i)
# Loop with else (executes if loop wasn't broken by break)
for i in range(3):
print(i)
else:
print("Loop completed normally")
# Functions and modules in Python
# Functions in Python
def greet(name):
"""Function for greeting"""
print(f"Hello, {name}!")
greet("Alex")
# Function with default parameters
def greet_with_message(name, message="Welcome!"):
print(f"Hello, {name}! {message}")
greet_with_message("Maria")
greet_with_message("John", "Nice to see you!")
# Function with arbitrary number of arguments
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")
# Function with keyword arguments
def user_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
user_info(name="Alex", age=30, city="New York")
# Function returning multiple values
def get_dimensions():
width = 100
height = 50
return width, height
w, h = get_dimensions()
print(f"Width: {w}, Height: {h}")
# Modules in Python
# To use external modules, you need to import them
import math
# Example of using math module to calculate square root
num = 25
print(f"Square root of {num}: {math.sqrt(num)}")
# Importing specific functions from a module
from random import randint, choice
print(f"Random number from 1 to 10: {randint(1, 10)}")
print(f"Random fruit: {choice(['apple', 'pear', 'banana'])}")
# Import with alias
import datetime as dt
now = dt.datetime.now()
print(f"Current date and time: {now}")
# Indentation and comments in Python
# In Python, code blocks are defined by indentation
# For example, all lines inside a function or loop must be indented 4 spaces or 1 tab
def greet(name):
# This is a comment. It explains what the next line of code does
print(f"Hello, {name}!") # Print greeting
greet("Alex")
# Comments in Python start with the # symbol
# They are ignored by the interpreter but useful for explaining code
# Example of using indentation and comments in a loop
for i in range(3):
# Print current iteration
print(f"Iteration {i}")
# Next time we'll increment the counter
i += 1
# Multi-line comments using triple quotes
"""
This is a multi-line comment.
It can span multiple lines.
Often used for documenting functions and classes.
"""
# Nested code blocks require additional indentation
def outer_function():
print("This is the outer function")
def inner_function():
print("This is the nested function")
for i in range(2):
print(f"Nested loop, iteration {i}")
# Call the inner function
inner_function()
outer_function()
# Documenting code with docstrings
def calculate_area(radius):
"""
Calculates the area of a circle given its radius.
Arguments:
radius (float): The radius of the circle
Returns:
float: The area of the circle
"""
return 3.14159 * radius ** 2
help(calculate_area) # Display function documentation
# Lists and dictionaries in Python
# Lists - ordered, mutable collections
fruits = ["apple", "banana", "orange", "pear", "kiwi"]
# Accessing list elements
print(f"First element: {fruits[0]}")
print(f"Last element: {fruits[-1]}")
print(f"Elements 1 to 3: {fruits[1:4]}")
# Modifying list elements
fruits[1] = "grape"
print(f"Modified list: {fruits}")
# List methods
fruits.append("pineapple") # add to end
fruits.insert(1, "mango") # insert at index
fruits.remove("orange") # remove by value
popped = fruits.pop() # remove and return last element
print(f"Removed element: {popped}")
print(f"List after changes: {fruits}")
# List length
print(f"List size: {len(fruits)}")
# Sorting lists
fruits.sort()
print(f"Sorted list: {fruits}")
fruits.sort(reverse=True)
print(f"Reverse sorted list: {fruits}")
# List comprehensions
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(f"Squares of numbers: {squares}")
# Filtering with list comprehensions
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(f"Even numbers: {even_numbers}")
# Dictionaries - unordered collections of key-value pairs
person = {
"name": "Anna",
"age": 28,
"profession": "programmer",
"languages": ["Python", "JavaScript", "Java"]
}
# Accessing dictionary elements
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
# Safe access with get()
print(f"City: {person.get('city', 'not specified')}")
# Modifying and adding elements
person["age"] = 29
person["city"] = "New York"
print(f"Updated dictionary: {person}")
# Dictionary methods
keys = list(person.keys()) # get all keys
values = list(person.values()) # get all values
items = list(person.items()) # get key-value pairs
print(f"Keys: {keys}")
print(f"Values: {values}")
print(f"Pairs: {items}")
# Dictionary comprehension
square_dict = {x: x**2 for x in range(1, 6)}
print(f"Square dictionary: {square_dict}")
# Exception handling in Python
# Basic try-except structure
try:
# Code that might raise an exception
x = 10 / 0
except ZeroDivisionError:
# Handling a specific exception
print("Error: division by zero")
# Handling different types of exceptions
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("Error: not a number")
except ZeroDivisionError:
print("Error: division by zero")
# Handling multiple exceptions with one block
try:
# Some risky code
value = int("abc")
except (ValueError, TypeError):
print("Conversion error")
# Using else in exception handling
try:
number = 5
result = 100 / number
except ZeroDivisionError:
print("Division by zero")
else:
# Executes if no exception occurred
print(f"Division successful, result: {result}")
# Using finally
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
# Always executes, regardless of exception
# Good place to release resources
print("Operation completed")
try:
file.close()
except:
pass
# Creating custom exceptions
class NegativeValueError(Exception):
"""Exception raised for negative values"""
pass
def calculate_square_root(value):
if value < 0:
raise NegativeValueError("Cannot calculate square root of negative number")
return value ** 0.5
try:
result = calculate_square_root(-5)
except NegativeValueError as e:
print(f"Error: {e}")
# Using assert for condition checking
def divide(a, b):
assert b != 0, "Divisor cannot be zero"
return a / b
try:
result = divide(10, 0)
except AssertionError as e:
print(f"Assertion error: {e}")
# Classes and object-oriented programming in Python
# Class definition
class Person:
# Class attribute (shared by all instances)
species = "Homo sapiens"
# Class constructor
def __init__(self, name, age):
# Instance attributes
self.name = name
self.age = age
self._private_attr = "Private" # convention: not to be used externally
# Instance method
def introduce(self):
return f"Hello, my name is {self.name}, I'm {self.age} years old."
# Method with parameters
def celebrate_birthday(self):
self.age += 1
return f"{self.name} is now {self.age} years old!"
# Static method (doesn't require an instance)
@staticmethod
def is_adult(age):
return age >= 18
# Class method (works with the class, not an instance)
@classmethod
def from_birth_year(cls, name, birth_year, current_year=2023):
age = current_year - birth_year
return cls(name, age)
# Creating class instances
person1 = Person("Anna", 28)
person2 = Person("John", 35)
# Using methods and attributes
print(person1.introduce())
print(person2.introduce())
print(person1.celebrate_birthday())
print(f"Species: {Person.species}")
print(f"Is adult: {Person.is_adult(16)}")
# Creating an object using class method
person3 = Person.from_birth_year("Maria", 1995)
print(person3.introduce())
# Inheritance
class Student(Person):
def __init__(self, name, age, university):
# Call parent class constructor
super().__init__(name, age)
self.university = university
self.courses = []
# Override parent class method
def introduce(self):
base_intro = super().introduce()
return f"{base_intro} I study at {self.university}."
# New method
def enroll(self, course):
self.courses.append(course)
return f"{self.name} enrolled in {course}"
# Using the child class
student1 = Student("Alex", 20, "MIT")
print(student1.introduce())
print(student1.enroll("Python programming"))
print(f"Student's courses: {student1.courses}")
# Multiple inheritance
class Employee:
def __init__(self, salary):
self.salary = salary
def get_salary(self):
return f"Salary: ${self.salary}"
class TeachingAssistant(Student, Employee):
def __init__(self, name, age, university, salary):
Student.__init__(self, name, age, university)
Employee.__init__(self, salary)
def introduce(self):
student_intro = Student.introduce(self)
salary_info = self.get_salary()
return f"{student_intro} {salary_info}"
# Using a class with multiple inheritance
ta = TeachingAssistant("Paul", 22, "Stanford", 30000)
print(ta.introduce())
# Working with files in Python
# Opening a file using with (automatically closes the file)
try:
# Writing to a file
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Hello, world!\n")
file.write("This is an example of working with files in Python.\n")
# Writing multiple lines
lines = ["First line\n", "Second line\n", "Third line\n"]
file.writelines(lines)
print("File successfully written.")
# Reading the entire file
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print("\nFile contents (reading entire file):")
print(content)
# Reading a file line by line
with open("example.txt", "r", encoding="utf-8") as file:
print("\nFile contents (line by line):")
for line in file:
print(f">>> {line.strip()}")
# Reading lines into a list
with open("example.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
print("\nLines in a list:")
for i, line in enumerate(lines):
print(f"Line {i+1}: {line.strip()}")
# Appending to a file
with open("example.txt", "a", encoding="utf-8") as file:
file.write("This line was added later.\n")
print("\nLine added to file.")
# Reading file after appending
with open("example.txt", "r", encoding="utf-8") as file:
print("\nUpdated file contents:")
print(file.read())
# Working with binary files
with open("binary_example.bin", "wb") as file:
file.write(b'\x48\x65\x6c\x6c\x6f') # "Hello" in binary
with open("binary_example.bin", "rb") as file:
binary_data = file.read()
print("\nBinary data:", binary_data)
print("Decoded data:", binary_data.decode("utf-8"))
# Moving the file pointer
with open("example.txt", "r", encoding="utf-8") as file:
# Reading first 10 bytes
start_data = file.read(10)
print("\nFirst 10 bytes:", start_data)
# Moving to a specific position
file.seek(20)
position_data = file.read(10)
print("10 bytes from position 20:", position_data)
# Moving from current position
file.seek(5, 1) # 5 bytes forward from current position
relative_data = file.read(10)
print("10 bytes after moving:", relative_data)
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Insufficient permissions to work with the file.")
except Exception as e:
print(f"An error occurred: {e}")
Common Errors
SyntaxError: syntax error
Occurs when the code violates Python's syntax rules. This is one of the most common errors for beginners.
Example of code with an error:
# Missing colon after if
if x > 5
print("x is greater than 5")
# Incorrect quotes
print('Hello, "world!")
# Unclosed parenthesis
print("Result:", (10 + 5 * 2
Correct solution:
# Added colon after if
if x > 5:
print("x is greater than 5")
# Consistent quotes
print('Hello, "world!"')
# Closed parenthesis
print("Result:", (10 + 5 * 2))
Tips for fixing:
Carefully read the error message, it usually points to the line with the issue.
Check if all brackets are closed (round, square, curly).
Ensure that a colon follows conditional statements and function declarations.
Check quotes: they should be paired and of the same type (' or ").
Pay attention to spaces and indentation, especially at the beginning of lines.
NameError: name is not defined
Occurs when trying to use a variable or function that hasn't been defined.
Example of code with an error:
# Using a variable before defining it
print(message)
message = "Hello, world!"
# Typo in variable name
name = "Alex"
print(naem)
# Function not defined
result = calculate_sum(5, 10)
Correct solution:
# Define the variable first
message = "Hello, world!"
print(message)
# Fixing the typo
name = "Alex"
print(name)
# Define the function before using it
def calculate_sum(a, b):
return a + b
result = calculate_sum(5, 10)
Tips for fixing:
Ensure variables are defined before using them.
Check the spelling of variable names (Python is case-sensitive).
Check the scope of variables (local/global).
If using functions, ensure they are defined or imported.
Common cause: typos in names.
TypeError: incompatible data types
Occurs when trying to perform an operation with incompatible data types or passing the wrong type of argument to a function.
Example of code with an error:
# Adding a string and a number
age = 25
message = "I am " + age + " years old"
# Calling a method on an inappropriate type
numbers = 12345
first_digit = numbers[0]
# Passing the wrong type of argument
result = len(42)
Correct solution:
# Converting number to string
age = 25
message = "I am " + str(age) + " years old"
# Or better, use f-strings
message = f"I am {age} years old"
# Converting number to string to access index
numbers = 12345
first_digit = str(numbers)[0]
# Passing the correct type of argument
number_str = "42"
result = len(number_str)
Tips for fixing:
Use type conversion functions: str(), int(), float().
Pay attention to the error message, it usually points to incompatible types.
For debugging, use the type() function to check the type of a variable.
Remember that some methods only work with specific data types.
Use string formatting (f-strings, format()) for combining text and numbers.
IndexError: index out of range
Occurs when trying to access a list or string element with an index that is out of the valid range.
Example of code with an error:
# Accessing a non-existent list index
fruits = ["apple", "banana", "orange"]
print(fruits[3]) # Indexing starts at 0, max index is 2
# Accessing an index of an empty list
empty_list = []
first_item = empty_list[0]
# Erroneous loop going out of bounds
for i in range(5):
numbers = [1, 2, 3, 4]
print(numbers[i])
Correct solution:
# Using the correct index
fruits = ["apple", "banana", "orange"]
print(fruits[2]) # Gets "orange"
# Check if the list is empty before accessing an element
empty_list = []
if empty_list:
first_item = empty_list[0]
else:
print("List is empty")
# Iterate over the actual length of the list
numbers = [1, 2, 3, 4]
for i in range(len(numbers)):
print(numbers[i])
# Or better, use direct iteration over elements
for number in numbers:
print(number)
Tips for fixing:
Remember that Python indices start at 0.
Ensure the index does not exceed len(collection) - 1.
Use the len() function to determine the size of the collection.
Use for-each loops instead of indices when possible.
Use try-except or check the index before accessing to prevent errors.
IndentationError: indentation error
Occurs when indentation is used incorrectly in the code. In Python, indentation is crucial for defining code blocks.
Example of code with an error:
# Inconsistent indentation in an if block
if True:
print("This is the first line")
print("This is the second line") # Incorrect indentation
# Missing indentation in a loop block
for i in range(3):
print(i) # No indentation
# Mixing tabs and spaces
def example():
print("This line uses spaces")
print("This line uses tabs")
Correct solution:
# Consistent indentation
if True:
print("This is the first line")
print("This is the second line") # Correct indentation
# Proper indentation in a loop block
for i in range(3):
print(i) # Added indentation
# Using only spaces (recommended by PEP 8)
def example():
print("This line uses spaces")
print("This line also uses spaces")
Tips for fixing:
Use only spaces (preferred) or only tabs, but don't mix them.
PEP 8 recommends using 4 spaces for each level of indentation.
Configure your code editor to automatically use correct indentation.
All lines in the same code block should have the same indentation.
After a colon (:), in conditions, loops, and functions, a code block with indentation should follow.
ImportError/ModuleNotFoundError: import error
Occurs when trying to import a module that is not installed or not found, or when there is a typo in the module name.
Example of code with an error:
# Trying to import a non-existent module
import non_existent_module
# Typo in module name
import padas # Instead of pandas
# Incorrect import from module
from math import factorial, squareroot # No function squareroot
Correct solution:
# Install the module before importing
# pip install requests
import requests
# Fixing the typo in module name
import pandas
# Correct import from module
from math import factorial, sqrt # sqrt instead of squareroot
# Check if the module exists before importing
try:
import matplotlib.pyplot as plt
except ImportError:
print("Module matplotlib is not installed. Install it with pip install matplotlib")
Tips for fixing:
Ensure the module is installed (use pip install for external modules).
Check the spelling of the module name.
Ensure the module is in Python's accessible path (PYTHONPATH).
Check the module's documentation for correct function and class names you are importing.
Use try-except to handle possible import errors.
KeyError: key error
Occurs when trying to access a non-existent key in a dictionary.
Example of code with an error:
# Accessing a non-existent key
user = {"name": "Alex", "age": 30}
print(user["email"]) # Key "email" does not exist
# Typo in key name
settings = {"timeout": 30, "retry_count": 3}
print(settings["time_out"]) # Typo in "timeout"
# Deleting a non-existent key
config = {"debug": True, "logging": False}
del config["cache"] # Key "cache" does not exist
Correct solution:
# Using the get() method for safe access
user = {"name": "Alex", "age": 30}
email = user.get("email", "not specified") # Returns "not specified" if key doesn't exist
print(f"Email: {email}")
# Checking if the key exists
settings = {"timeout": 30, "retry_count": 3}
key = "time_out"
if key in settings:
print(settings[key])
else:
print(f"Key '{key}' not found")
# Safe deletion with check
config = {"debug": True, "logging": False}
key_to_delete = "cache"
if key_to_delete in config:
del config[key_to_delete]
else:
print(f"Key '{key_to_delete}' does not exist and cannot be deleted")
Tips for fixing:
Use the get() method for dictionaries instead of direct access (dict[key]), it allows specifying a default value.
Check if the key exists using the in operator before accessing it.
Pay attention to case and typos in key names.
Use try-except to handle possible missing keys.
For debugging, print all dictionary keys using dict.keys().
AttributeError: attribute error
Occurs when trying to access a non-existent attribute or method of an object.
Example of code with an error:
# Calling a non-existent method
text = "hello"
uppercase_text = text.capitalize_all() # No such method
# Typo in method name
numbers = [1, 2, 3]
numbers.ad(4) # Instead of add or append
# Accessing an attribute of None
def get_user(user_id):
# Function returns None if user is not found
return None
user = get_user(123)
print(user.name) # Trying to access an attribute of None
Correct solution:
# Using an existing method
text = "hello"
uppercase_text = text.upper() # Correct method
# Fixing the typo
numbers = [1, 2, 3]
numbers.append(4) # Correct method for lists
# Checking for None before accessing an attribute
def get_user(user_id):
# Function returns None if user is not found
return None
user = get_user(123)
if user is not None:
print(user.name)
else:
print("User not found")
# Using hasattr to check for attribute existence
class Person:
def __init__(self, name):
self.name = name
person = Person("Anna")
if hasattr(person, "age"):
print(person.age)
else:
print("Attribute 'age' does not exist")
Tips for fixing:
Check the documentation or use the dir() function to view available attributes and methods.
Check the object's type using type() or isinstance() before using specific methods.
Check if the object is None before accessing its attributes.
Use the hasattr() function to check for attribute existence.
Pay attention to the error message, it usually indicates which method or attribute is missing.
Frequently Asked Questions
How do I use your online compiler?
Simply paste your Python code into the input field and click the "Run" button. The execution results will appear below almost instantly. It's an easy way to quickly test code snippets without installing Python on your device.
How does the service work?
Our free service is based on Pyodide — a project that allows Python to run in the browser using WebAssembly. This means you can execute Python code directly in your browser without needing to install Python on your computer.
Which Python version is used in the online compiler?
Our online compiler uses Python 3.8 — one of the most popular and stable versions of the language. It supports many modern features and libraries, allowing you to write efficient and readable code.
Which libraries are supported?
Many popular Python libraries are pre-installed, including:
NumPy: for working with multi-dimensional arrays and performing mathematical operations.
Pandas: for analyzing and processing data in tabular format.
SciPy: for scientific computing based on NumPy.
Matplotlib: for creating graphs and data visualizations.
Scikit-learn: for machine learning and data analysis.
Requests: for working with HTTP requests.
Flask: for creating simple web applications.
Django: for developing more complex web applications.
PyTest: for testing code.
LXML: for parsing XML and HTML documents.
PyYAML: for working with YAML files.
Regex: for working with regular expressions.
Cryptography: for cryptography operations.
BeautifulSoup4: for parsing HTML and XML documents.
SQLAlchemy: for working with databases.
Pillow: for image processing.
SymPy: for symbolic computations.
NetworkX: for analyzing network structures and graphs.
Pyodide: for working with Pyodide and WebAssembly.
Micropip: for installing additional packages from PyPI.
By default, your code is not saved after closing the browser. We recommend exporting or saving your code to a file on your device.
Is it safe to use the editor and compiler?
We don't store your code on our server, and all processing happens only in your browser, so your code is only accessible to you. However, for working with confidential or sensitive information, we recommend using a local environment or secure cloud services.
What are the limitations?
There are a few limitations:
Execution time limit: to avoid browser overload, code execution is limited in time.
Memory limit: since the code runs in the browser, there are limitations on the amount of available memory.
Also, resource-intensive operations with large data may run slowly.
How do I debug code?
You can use standard Python debugging methods, such as print() to output intermediate results. The traceback function is also available for detailed error information. In the future, we plan to add support for more advanced debugging tools.
Start coding in Python right now
Whether you're just starting to learn programming or already have experience, our online Python compiler will help you write, test, and improve your code in a convenient environment without complex setup.