Python Tutorial

Python Examples

145 short programs you can run in the Python editor. Change a value, press Run, and read the print (or the plot).

145 copy-and-run snippets. Open one in Try Python at /try, change a value, and run it again. Each language has its own shelf and its own editor.

Basics

Swap two names

left, right = 3, 9
left, right = right, left
print(left, right)
Related lesson →

Strings

Lists

Append and insert

nums = [1, 2]
nums.append(3)
nums.insert(0, 0)
print(nums)
Related lesson →

Remove and pop

nums = [1, 2, 3, 2]
nums.remove(2)
print(nums.pop())
print(nums)
Related lesson →

List comprehension

squares = [n * n for n in range(1, 6)]
print(squares)
Related lesson →

Enumerate

for i, name in enumerate(["Ada", "Grace"], start=1):
    print(i, name)
Related lesson →

Zip two lists

names = ["Luna", "Kai"]
scores = [88, 92]
for name, score in zip(names, scores):
    print(name, score)
Related lesson →

Slice a list

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])
print(nums[::2])
Related lesson →

Tuples and sets

Dictionaries

Dict get with default

user = {"name": "Kai"}
print(user.get("score", 0))
Related lesson →

Add a dict key

user = {"name": "Luna"}
user["city"] = "Oslo"
print(user)
Related lesson →

Remove a dict key

user = {"name": "Ada", "role": "dev"}
user.pop("role")
print(user)
Related lesson →

Loop dict items

for key, value in {"a": 1, "b": 2}.items():
    print(key, value)
Related lesson →

Dict keys and values

data = {"n": 3, "m": 9}
print(list(data.keys()))
print(list(data.values()))
Related lesson →

Nested dict

team = {"lead": {"name": "Ada", "year": 2026}}
print(team["lead"]["name"])
Related lesson →

Control flow

Elif chain

score = 82
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("C")
Related lesson →

Match case

status = "ok"
match status:
    case "ok":
        print("ready")
    case _:
        print("wait")
Related lesson →

FizzBuzz

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
Related lesson →

Else on a for loop

for n in [2, 3, 5]:
    if n == 4:
        break
else:
    print("4 was not found")
Related lesson →

Functions

Define a function

def greet(name):
    return f"Welcome, {name}!"

print(greet("Ada"))
Related lesson →

Default argument

def greet(name="friend"):
    return f"Hi, {name}"

print(greet())
print(greet("Kai"))
Related lesson →

Return two values

def bounds(nums):
    return min(nums), max(nums)

print(bounds([4, 17, 9]))
Related lesson →

Keyword args

def label(name, **meta):
    return f"{name} {meta}"

print(label("task", done=True, n=3))
Related lesson →

Map and filter

nums = [1, 2, 3, 4, 5]
print(list(map(lambda n: n * 2, nums)))
print(list(filter(lambda n: n > 2, nums)))
Related lesson →

Recursion factorial

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

print(factorial(5))
Related lesson →

Docstring

def area(w, h):
    """Return width times height."""
    return w * h

print(area.__doc__)
print(area(3, 4))
Related lesson →

Inner function

def make_adder(n):
    def add(x):
        return x + n
    return add

plus3 = make_adder(3)
print(plus3(10))
Related lesson →

OOP

Simple class

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)
print(p.x, p.y)
Related lesson →

Class method

class Total:
    def __init__(self):
        self.sum = 0
    def add(self, n):
        self.sum += n

t = Total()
t.add(4)
t.add(7)
print(t.sum)
Related lesson →

Inheritance

class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "woof"

print(Dog().speak())
Related lesson →

Str representation

class User:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f"User({self.name})"

print(User("Ada"))
Related lesson →

Class attribute

class Counter:
    count = 0
    def __init__(self):
        Counter.count += 1

Counter()
Counter()
print(Counter.count)
Related lesson →

Iterator protocol

class Count:
    def __init__(self, n):
        self.n = n
        self.i = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.i >= self.n:
            raise StopIteration
        self.i += 1
        return self.i

print(list(Count(4)))
Related lesson →

Polymorphism

class Square:
    def area(self):
        return 9
class Circle:
    def area(self):
        return 28

for shape in (Square(), Circle()):
    print(shape.area())
Related lesson →

Dataclass-like dict

person = dict(name="Mia", score=95)
print(person["name"])
Related lesson →

Files and JSON

JSON loads

import json
data = json.loads('{"name": "Kai", "score": 92}')
print(data["name"], data["score"])
Related lesson →

Pretty JSON

import json
print(json.dumps({"a": 1, "b": [2, 3]}, indent=2))
Related lesson →

Read from a string file

from io import StringIO
buf = StringIO("alpha\nbeta\n")
print(buf.read())
Related lesson →

Write lines in memory

from io import StringIO
buf = StringIO()
buf.write("one\n")
buf.write("two\n")
print(buf.getvalue())
Related lesson →

Errors and modules

Try except

try:
    print(int("grid"))
except ValueError:
    print("not a number")
Related lesson →

Try except else

try:
    n = int("12")
except ValueError:
    print("fail")
else:
    print(n * 2)
Related lesson →

Raise an error

def positive(n):
    if n < 0:
        raise ValueError("need a positive number")
    return n

try:
    positive(-1)
except ValueError as err:
    print(err)
Related lesson →

Random choice

import random
random.seed(1)
print(random.choice(["A", "B", "C"]))
Related lesson →

Datetime today

from datetime import date
print(date(2026, 8, 19).isoformat())
Related lesson →

Timedelta

from datetime import date, timedelta
print(date(2026, 8, 19) + timedelta(days=7))
Related lesson →

Regex findall

import re
print(re.findall(r"[A-Z][a-z]+", "Ada and Grace"))
Related lesson →

Statistics mean

import statistics
print(statistics.mean([88, 92, 79, 95]))
Related lesson →

Sorted with key

names = ["mia", "Ada", "kai"]
print(sorted(names, key=str.lower))
Related lesson →

DSA

Stack with a list

stack = []
stack.append("a")
stack.append("b")
print(stack.pop())
print(stack)
Related lesson →

Queue with deque

from collections import deque
q = deque([1, 2])
q.append(3)
print(q.popleft())
print(list(q))
Related lesson →

Linear search

def find(nums, target):
    for i, n in enumerate(nums):
        if n == target:
            return i
    return -1

print(find([4, 17, 9], 9))
Related lesson →

Binary search

import bisect
nums = [1, 4, 9, 16]
print(bisect.bisect_left(nums, 9))
Related lesson →

Bubble sort

nums = [9, 2, 7, 1]
for i in range(len(nums)):
    for j in range(len(nums) - 1):
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(nums)
Related lesson →

Linked-list node

class Node:
    def __init__(self, value, nxt=None):
        self.value = value
        self.next = nxt

head = Node(1, Node(2, Node(3)))
while head:
    print(head.value)
    head = head.next
Related lesson →

Set for uniqueness

seen = set()
for n in [1, 2, 1, 3]:
    if n not in seen:
        seen.add(n)
print(sorted(seen))
Related lesson →

Frequency map

from collections import Counter
print(Counter([3, 1, 3, 2, 1, 3]))
Related lesson →

Data science

NumPy array stats

import numpy as np
scores = np.array([88, 92, 79, 95])
print(scores.mean(), scores.max())
Related lesson →

NumPy vector math

import numpy as np
a = np.array([1, 2, 3])
print(a * 2 + 1)
Related lesson →

Pandas DataFrame

import pandas as pd
df = pd.DataFrame({"name": ["Luna", "Kai", "Mia"], "score": [88, 92, 95]})
print(df)
Related lesson →

Pandas describe

import pandas as pd
df = pd.DataFrame({"score": [88, 92, 79, 95]})
print(df.describe())
Related lesson →

Pandas filter

import pandas as pd
df = pd.DataFrame({"name": ["Ada", "Kai"], "score": [99, 72]})
print(df[df["score"] >= 80])
Related lesson →

Matplotlib line

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [3, 8, 4, 9])
plt.title("Weekly signups")
plt.show()
Related lesson →

Matplotlib bar

import matplotlib.pyplot as plt
plt.bar(["A", "B", "C"], [4, 7, 2])
plt.title("Tickets")
plt.show()
Related lesson →

Matplotlib scatter

import matplotlib.pyplot as plt
plt.scatter([1, 2, 3, 4], [2, 1, 4, 3])
plt.title("Points")
plt.show()
Related lesson →

FAQ: Python Examples

Common questions about this page.

What will I learn in this Python Examples?

This Python Examples on StudyGrid covers python examples step by step. 145 short programs you can run in the Python editor. Change a value, press Run, and read the print (or the plot). Each chapter includes syntax notes and examples you can copy and run.

Should I run python examples examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python examples in this Examples Python lesson (Python Examples).

Is this Python Examples for beginners?

Yes. The Python Examples is written for beginners and also works as a reference. Start at the first chapter, then follow the sidebar in order.

How do I start this Examples tutorial?

Open the first lesson from this Python Examples page or the left sidebar. Read the explanation, run the example, then use Next to continue the Examples path.

Are python examples examples included?

Yes. StudyGrid includes python examples examples on this path. Use them to practice Python and compare your output with the sample results.

Is the Python Examples free?

Yes. This Examples tutorial is free on StudyGrid (studygrid.in). You do not need to pay to read the lessons or copy the examples.