Bookmark this page
Python Playground
Practice Python in the browser
Code Runner
You can practice by running code using our code runner.
Table of Contents
- Basics
- Control Flow
- Data Structures
- Functions & Modules
- Object-Oriented Programming
- Advanced / Misc
- Data Analysis
Basics
Hello World
# Hello World print("Hello from code sample!")
Variables & Types
# Variables, Types, and Simple Math x = 10 y = 3.14 text = "Python" print(x, y, text) print(type(x), type(y), type(text)) # Simple Math sum_xy = x + y print("x + y =", sum_xy)
Type Conversions
# Explicit & Implicit Conversions a = "42" # string b = 8 # integer # Explicit num_a = int(a) # convert string to int print("Result of num_a + b:", num_a + b) # Implicit might happen in some contexts, but Python is fairly strict # For instance, str + int won't automatically convert, so we must do it ourselves: print("Combined string:", a + str(b))
String Manipulation
# String Manipulation message = "Hello, World!" print("Original:", message) print("Lowercase:", message.lower()) print("Uppercase:", message.upper()) print("Substring:", message[0:5]) # 'Hello' print("Split:", message.split(",")) # ['Hello', ' World!'] print("Replace:", message.replace("World", "Python"))
Strings Advanced
# Strings Advanced message = "Concatenation " + "example!" formatted = f"This is {message} with an integer {42}" multi_line = """This is multiple lines""" print("Joined string:", formatted) print("Multiline string:\n", multi_line) # Center & count print("Centered:", message.center(30, '*')) print("Count of 'a':", message.count('a'))
Control Flow
If-Else, Elif
# If-Else and Elif age = 18 if age < 18: print("Minor") elif age == 18: print("Just turned adult") else: print("Adult")
Loops (For, While)
# For, While, and Range print("For loop from 0 to 4:") for i in range(5): print(i) print("While loop example:") j = 0 while j < 3: print("j =", j) j += 1
Loops Advanced
# Loops Advanced items = [("apple", 3), ("banana", 2), ("cherry", 5)] # Using enumerate for index, (fruit, qty) in enumerate(items): print(f"Item #{index} is {fruit} with qty {qty}") # Using zip names = ["Alice", "Bob", "Charlie"] scores = [90, 85, 92] for n, s in zip(names, scores): print(n, "scored", s) # Break & Continue for i in range(1, 6): if i == 3: continue if i == 5: break print(i)
Data Structures
Lists
# Lists: creation, indexing, slicing fruits = ["apple", "banana", "cherry"] fruits.append("date") print("Fruits:", fruits) print("First fruit:", fruits[0]) print("Slice (1:3):", fruits[1:3]) # banana, cherry # List comprehension numbers = [x for x in range(5)] print("List comprehension:", numbers)
Lists Advanced
# Lists Advanced nums = [1, 2, 3, 4, 5] nums[2:4] = [9, 9] # in-place replacement print("Modified list:", nums) # Sorting with a key words = ["apple", "bat", "atom", "banana"] words.sort(key=len) print("Sorted by length:", words) # map & filter squared = list(map(lambda x: x*x, nums)) filtered = list(filter(lambda x: x > 2, nums)) print("Squared:", squared) print("Filtered > 2:", filtered)
Tuples & Sets
# Tuples & Sets my_tuple = (1, 2, 3) print("Tuple:", my_tuple) # my_tuple[0] = 99 # This would error, tuples are immutable my_set = {1, 2, 2, 3, 4} my_set.add(5) print("Set (unique values):", my_set) print("Does the set contain 2?", 2 in my_set)
Tuples & Sets Advanced
# Tuple & Set Advanced nested_tuple = ((1, 2), (3, 4)) print("Nested tuple:", nested_tuple) # Set operations setA = {1, 2, 3} setB = {3, 4, 5} print("Union:", setA | setB) print("Intersection:", setA & setB) print("Difference:", setA - setB)
Dictionaries
# Dictionaries person = {"name": "Alice", "age": 30} person["city"] = "New York" print("Person dictionary:", person) print("Name:", person["name"]) print("Keys:", person.keys()) print("Values:", person.values())
Dictionaries Advanced
# Dictionaries Advanced person = {"name": "Alice", "age": 30, "city": "NY"} print("Country:", person.get("country", "Unknown")) # dictionary comprehension squares = {x: x*x for x in range(1,6)} print("Squares dict:", squares) # Merging dictionaries (Python 3.9+) extra = {"job": "Engineer"} merged = {**person, **extra} print("Merged dict:", merged)
Functions & Modules
Defining Functions
# Defining Functions def greet(name): return f"Hello, {name}!" message = greet("Alice") print(message) # Function with default parameter def power(base, exponent=2): return base ** exponent print("power(5) =", power(5)) # uses exponent=2 print("power(5,3) =", power(5, 3)) # custom exponent
Functions Advanced
# Functions Advanced # *args and **kwargs def demo_args(*args, **kwargs): print("args:", args) print("kwargs:", kwargs) demo_args(1, 2, 3, name="Bob", job="Developer") # Nested function def outer(x): def inner(y): return x + y return inner add_to_5 = outer(5) print("Result from nested function:", add_to_5(10))
Importing Modules
# Importing Modules import math print("math.sqrt(16) =", math.sqrt(16)) print("math.pi =", math.pi) # You can also do: from math import pi, sqrt
Modules Advanced
# Modules Advanced import math import random # Checking Python version print("Python version:", __import__('sys').version) # random usage for i in range(3): print("Random float 0-1:", random.random()) # math.comb in Python 3.8+ (binomial coefficient) print("Combinations of 5 choose 2:", math.comb(5,2))
Object-Oriented Programming
Classes and Inheritance
# Classes and Objects (OOP) class Animal: def __init__(self, name): self.name = name def speak(self): print(self.name, "makes a noise.") class Dog(Animal): def speak(self): print(self.name, "barks!") dog = Dog("Rex") dog.speak()
OOP Advanced
# OOP Advanced class Shape: def area(self): raise NotImplementedError("Please implement 'area' method") class Rectangle(Shape): def __init__(self, w, h): self.w = w self.h = h @property def area(self): return self.w * self.h rect = Rectangle(3, 4) print("Rectangle area:", rect.area) # Class & static methods class MyClass: class_var = 10 @classmethod def class_method(cls): print("class_var =", cls.class_var) @staticmethod def static_method(): print("Static method called") MyClass.class_method() MyClass.static_method()
Advanced / Misc
Exception Handling
# Exceptions and Try-Except try: num = int("abc") # invalid integer except ValueError as e: print("Caught ValueError:", e) finally: print("This finally block always executes.")
List Comprehensions
# More on List Comprehensions numbers = [1, 2, 3, 4, 5] squares = [n*n for n in numbers] evens = [n for n in numbers if n % 2 == 0] print("Numbers:", numbers) print("Squares:", squares) print("Evens:", evens)
Data Analysis
NumPy Basics
# NumPy Basics import numpy as np arr = np.array([1, 2, 3, 4]) print("NumPy Array:", arr) # Some operations print("Shape:", arr.shape) print("Mean:", arr.mean()) print("Sum:", arr.sum())
NumPy Advanced
# NumPy Advanced import numpy as np # Create a 3x3 random matrix matrix = np.random.randn(3, 3) print("Random 3x3 matrix:\n", matrix) # Matrix multiplication mat2 = np.array([[1,2,1], [0,1,0], [2,1,2]]) result = matrix.dot(mat2) print("\nMatrix multiplication result:\n", result) # Fancy indexing / slicing first_col = matrix[:, 0] print("\nFirst column:", first_col) # Conditional selection above_zero = matrix[matrix > 0] print("\nElements above 0:", above_zero)
Pandas Basics
# Pandas Basics import pandas as pd data = { "Name": ["Alice", "Bob", "Charlie"], "Age": [25, 32, 18], "City": ["New York", "Paris", "London"] } df = pd.DataFrame(data) print("DataFrame:") print(df) print() print("Describe:") print(df.describe())
Pandas Advanced
# Pandas Advanced import pandas as pd # Sample data sales = { "Store": ["A", "A", "B", "B", "C"], "Month": ["Jan", "Feb", "Jan", "Feb", "Jan"], "Revenue": [100, 150, 80, 120, 200] } df = pd.DataFrame(sales) print("Original sales DataFrame:") print(df) print() # Grouping by Store grouped = df.groupby("Store")["Revenue"].sum() print("Total revenue per Store:") print(grouped) print() # Pivot Table pivot = df.pivot_table(values="Revenue", index="Store", columns="Month", aggfunc="sum", fill_value=0) print("Pivot Table:") print(pivot) print() # Sorting sorted_df = df.sort_values(by="Revenue", ascending=False) print("Sorted by Revenue (descending):") print(sorted_df)