Library Home

Tutorials & Programs

Search. Build. Master.

Type any Python program you want to learn — "print 1 to 10", "fibonacci", "scrape webpage" — and read it explained step-by-step.

Beginner

Print Hello, World!

The classic first program — proves your Python setup works.

  1. 1Open a new file called hello.py.
  2. 2Call the built-in print() function with the text you want to show.
  3. 3Run the file with `python hello.py`.
code · python
print("Hello, World!")
output
Hello, World!
Beginner

Print numbers from 1 to 10

Use a for-loop with range() to walk through the numbers 1 to 10 and print each one.

  1. 1range(1, 11) produces 1, 2, 3 ... 10 (the stop value 11 is excluded).
  2. 2Each loop iteration assigns the next number to the variable i.
  3. 3print(i) shows the number on its own line.
code · python
for i in range(1, 11):
    print(i)
output
1
2
3
4
5
6
7
8
9
10
Beginner

Check if a number is even or odd

Use the modulo operator (%) — the remainder after division by 2.

  1. 1Take input from the user and convert it to int.
  2. 2n % 2 == 0 means the number is even.
  3. 3Otherwise it's odd.
code · python
n = int(input("Enter a number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
Beginner

Sum of numbers from 1 to N

Accumulate a running total inside a loop.

  1. 1Start with total = 0.
  2. 2Loop from 1 to n (inclusive) using range(1, n+1).
  3. 3Add each i to total.
code · python
n = int(input("N: "))
total = 0
for i in range(1, n + 1):
    total += i
print("Sum =", total)
Beginner

Factorial of a number

Factorial of n is 1 × 2 × 3 × … × n. We multiply in a loop.

  1. 1Initialize fact = 1.
  2. 2Multiply fact by every i from 2 up to n.
  3. 3Print the result.
code · python
n = int(input("N: "))
fact = 1
for i in range(2, n + 1):
    fact *= i
print(fact)
Beginner

Fibonacci sequence (first N terms)

Each Fibonacci number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8…

  1. 1Start with a = 0, b = 1.
  2. 2On each step, print a, then set (a, b) = (b, a + b).
  3. 3Repeat n times.
code · python
n = int(input("Terms: "))
a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
Intermediate

Check if a number is prime

A prime number > 1 has no divisors other than 1 and itself.

  1. 1Numbers ≤ 1 are not prime.
  2. 2Test divisibility from 2 up to √n — if any divides n, it's not prime.
  3. 3Otherwise it's prime.
code · python
n = int(input("N: "))
is_prime = n > 1
for i in range(2, int(n ** 0.5) + 1):
    if n % i == 0:
        is_prime = False
        break
print("prime" if is_prime else "not prime")
Beginner

Reverse a string

Use slicing with a step of -1 to reverse any sequence.

  1. 1Take a string from the user.
  2. 2Use s[::-1] to get its reverse.
  3. 3Print it.
code · python
s = input("Text: ")
print(s[::-1])
Beginner

Check if a string is a palindrome

A palindrome reads the same forwards and backwards.

  1. 1Lowercase the string to ignore case.
  2. 2Compare it with its reverse s[::-1].
code · python
s = input("Text: ").lower()
print("palindrome" if s == s[::-1] else "not a palindrome")
Beginner

Find the largest number in a list

Walk through the list and track the biggest value seen so far.

  1. 1Start with biggest = first element.
  2. 2Loop through the rest; update biggest if x > biggest.
code · python
nums = [3, 7, 2, 9, 4]
biggest = nums[0]
for x in nums[1:]:
    if x > biggest:
        biggest = x
print(biggest)
Beginner

Count vowels in a string

Iterate through the string and increase a counter when the char is in 'aeiou'.

  1. 1Lowercase the input.
  2. 2For each character, check if it's in the vowels set.
code · python
s = input("Text: ").lower()
count = sum(1 for c in s if c in "aeiou")
print(count)
Beginner

Swap two variables

Python lets you swap with a single tuple assignment.

  1. 1Use a, b = b, a — Python handles it without a temp variable.
code · python
a, b = 5, 9
a, b = b, a
print(a, b)
Beginner

Multiplication table of N

Print N × 1 through N × 10 using a for-loop.

  1. 1Loop i from 1 to 10.
  2. 2Print f'{n} x {i} = {n*i}'.
code · python
n = int(input("N: "))
for i in range(1, 11):
    print(f"{n} x {i} = {n*i}")
Intermediate

GCD of two numbers (Euclidean)

Repeatedly replace the larger number with the remainder.

  1. 1While b ≠ 0, set (a, b) = (b, a % b).
  2. 2When b is 0, a is the GCD.
code · python
a, b = 48, 18
while b:
    a, b = b, a % b
print("GCD =", a)
Beginner

Check if a year is a leap year

Leap year: divisible by 4, but not by 100 unless also by 400.

  1. 1Read the year as int.
  2. 2Apply the rule with `and` / `or`.
code · python
y = int(input("Year: "))
leap = (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
print("leap" if leap else "not leap")
Beginner

Simple calculator (+ − × ÷)

Wrap each operation in a function and choose with a dictionary.

  1. 1Define four small functions.
  2. 2Map the operator symbol to the function.
  3. 3Call and print.
code · python
def add(a,b): return a+b
def sub(a,b): return a-b
def mul(a,b): return a*b
def div(a,b): return a/b
ops = {"+": add, "-": sub, "*": mul, "/": div}
a = float(input("a: "))
op = input("op: ")
b = float(input("b: "))
print(ops[op](a, b))
Intermediate

Guess the number game

The computer picks a secret number; the player guesses with hints.

  1. 1Pick a random integer with random.randint.
  2. 2Loop until the guess equals the secret.
  3. 3Print higher/lower hints.
code · python
import random
secret = random.randint(1, 100)
while True:
    g = int(input("Guess: "))
    if g == secret:
        print("Got it!")
        break
    print("higher" if g < secret else "lower")
Intermediate

Word frequency in text

Use a dictionary (or Counter) to count occurrences.

  1. 1Split the text on whitespace.
  2. 2Use collections.Counter for an instant tally.
code · python
from collections import Counter
text = "the quick brown fox jumps over the lazy fox"
print(Counter(text.split()))
Beginner

Read a text file line by line

open() with a `with` block guarantees the file is closed.

  1. 1Open the file in read mode.
  2. 2Iterate the file object — each iteration is a line.
code · python
with open("notes.txt") as f:
    for line in f:
        print(line.rstrip())
Beginner

Write text to a file

Open in 'w' mode (overwrites) or 'a' (appends).

  1. 1Open with mode='w'.
  2. 2Call f.write("…") with your text.
code · python
with open("note.txt", "w") as f:
    f.write("Hello from Pynexa\n")
Intermediate

Read and write JSON

Use the json module to serialize Python dicts/lists to JSON and back.

  1. 1json.dump(obj, f) to save.
  2. 2json.load(f) to load.
  3. 3Use indent=2 for readable output.
code · python
import json
data = {"name": "Sky", "skills": ["py", "ts"]}
with open("u.json", "w") as f:
    json.dump(data, f, indent=2)
with open("u.json") as f:
    print(json.load(f))
Intermediate

Fetch data from an API

The `requests` library makes HTTP easy. Install with `pip install requests`.

  1. 1Call requests.get(url).
  2. 2Check .status_code.
  3. 3Parse JSON with .json().
code · python
import requests
r = requests.get("https://api.github.com/repos/python/cpython")
if r.status_code == 200:
    print(r.json()["stargazers_count"])
Beginner

Squares with list comprehension

List comprehensions are a compact way to build lists.

  1. 1[expr for x in iterable] runs expr for each x.
  2. 2Optionally add `if condition`.
code · python
squares = [x * x for x in range(1, 11)]
print(squares)
Intermediate

Define a class with methods

Classes group data and behavior. __init__ sets up new instances.

  1. 1Define class Name:
  2. 2Add __init__(self, ...) to store attributes.
  3. 3Add methods that take self.
code · python
class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        print(self.name, "woof!")

Dog("Rex").bark()
Intermediate

Inheritance — extend a class

A subclass reuses and overrides the parent class.

  1. 1Write class Sub(Parent):
  2. 2Override methods as needed.
  3. 3Use super().method() to call the parent.
code · python
class Animal:
    def speak(self): print("...")
class Cat(Animal):
    def speak(self): print("meow")
Cat().speak()
Advanced

Write a custom decorator

A decorator wraps a function to add behavior before/after it runs.

  1. 1Define wrapper(*a, **kw) inside an outer function.
  2. 2Return wrapper.
  3. 3Use @decorator above the target function.
code · python
def timed(fn):
    import time
    def wrap(*a, **kw):
        t = time.time()
        r = fn(*a, **kw)
        print(fn.__name__, round(time.time()-t, 4), "s")
        return r
    return wrap

@timed
def slow():
    sum(range(10**6))
slow()
Advanced

Generators with yield

Generators produce values lazily, one at a time, using `yield`.

  1. 1Replace return with yield to make the function a generator.
  2. 2Iterate with a for-loop.
code · python
def squares(n):
    for i in range(n):
        yield i * i

for s in squares(5):
    print(s)
Intermediate

Handle errors with try/except

Wrap risky code in try; catch specific exceptions to recover gracefully.

  1. 1try: risky code.
  2. 2except ValueError: handle bad input.
  3. 3else / finally as needed.
code · python
try:
    x = int(input("number: "))
    print(10 / x)
except ValueError:
    print("not a number")
except ZeroDivisionError:
    print("can't divide by zero")
Intermediate

Bubble sort a list

Repeatedly swap adjacent pairs that are in the wrong order.

  1. 1Loop n−1 passes.
  2. 2Inside, compare each adjacent pair and swap if needed.
code · python
nums = [5, 2, 8, 1, 4]
n = len(nums)
for i in range(n - 1):
    for j in range(n - 1 - i):
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(nums)
Advanced

Binary search

Search a sorted list in O(log n) by halving the range each step.

  1. 1Keep lo and hi pointers.
  2. 2Look at mid; move lo or hi based on comparison.
code · python
def bsearch(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target: return mid
        if arr[mid] < target: lo = mid + 1
        else: hi = mid - 1
    return -1
print(bsearch([1,3,5,7,9,11], 7))
Intermediate

Recursive factorial

A function that calls itself with a smaller problem until a base case.

  1. 1Base case: factorial(0) = 1.
  2. 2Recursive case: n * factorial(n−1).
code · python
def fact(n):
    return 1 if n == 0 else n * fact(n - 1)
print(fact(6))
Intermediate

Transpose a matrix

Use zip(*matrix) to flip rows and columns in one line.

  1. 1zip(*m) yields tuples of the columns.
  2. 2Wrap each in list() if you want lists.
code · python
m = [[1,2,3],[4,5,6]]
t = [list(r) for r in zip(*m)]
print(t)
Advanced

Extract emails from text (regex)

Use the `re` module to match patterns inside text.

  1. 1Define a pattern with re.compile.
  2. 2Call findall on your text.
code · python
import re
text = "Mail me at hi@pynexa.dev or admin@example.com"
print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.-]+", text))
Intermediate

Read a CSV file

csv.DictReader turns each row into a dictionary keyed by the header.

  1. 1Open the CSV.
  2. 2Iterate the DictReader.
code · python
import csv
with open("data.csv") as f:
    for row in csv.DictReader(f):
        print(row)
Advanced

Run tasks in parallel with threads

threading.Thread runs functions concurrently — great for I/O-bound work.

  1. 1Create Thread(target=fn).
  2. 2Call .start() then .join().
  3. 3Repeat for multiple workers.
code · python
import threading, time
def work(name):
    time.sleep(1); print(name, "done")
ts = [threading.Thread(target=work, args=(f"t{i}",)) for i in range(3)]
for t in ts: t.start()
for t in ts: t.join()
Advanced

Async functions with asyncio

asyncio lets a single thread juggle many awaiting tasks (perfect for network I/O).

  1. 1Mark functions with async def.
  2. 2Use await inside them.
  3. 3Run with asyncio.run(main()).
code · python
import asyncio
async def greet(name):
    await asyncio.sleep(1)
    print("hi", name)
async def main():
    await asyncio.gather(greet("a"), greet("b"))
asyncio.run(main())
Advanced

Tiny web server with Flask

Flask spins up a real HTTP server in 6 lines. Install: pip install flask.

  1. 1Create app = Flask(__name__).
  2. 2Decorate functions with @app.route.
  3. 3Run with app.run().
code · python
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Pynexa!"

if __name__ == "__main__":
    app.run(debug=True)
Intermediate

Build a window with Tkinter

Tkinter ships with Python — perfect for tiny desktop apps.

  1. 1Create a root window.
  2. 2Add widgets like Label/Button.
  3. 3Call root.mainloop().
code · python
import tkinter as tk
root = tk.Tk()
root.title("Pynexa")
tk.Label(root, text="Hello!").pack(padx=20, pady=20)
tk.Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()
Advanced

Scrape a webpage with BeautifulSoup

Download a page with requests, then parse the HTML with bs4.

  1. 1pip install requests beautifulsoup4.
  2. 2Fetch the URL.
  3. 3Use BeautifulSoup to query tags.
code · python
import requests
from bs4 import BeautifulSoup
html = requests.get("https://example.com").text
soup = BeautifulSoup(html, "html.parser")
print(soup.title.text)
Advanced

NumPy array basics

NumPy gives you fast n-dimensional arrays. Install: pip install numpy.

  1. 1Create with np.array.
  2. 2Vectorize math — no loops needed.
  3. 3Use shape, mean, dot, etc.
code · python
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b, a.dot(b), a.mean())
Advanced

Pandas DataFrame basics

Pandas is the de-facto data analysis library. Install: pip install pandas.

  1. 1Create a DataFrame from a dict.
  2. 2Filter rows, compute columns, group.
  3. 3Save to CSV with to_csv.
code · python
import pandas as pd
df = pd.DataFrame({"name": ["a","b","c"], "score": [3, 7, 5]})
print(df[df.score > 4])
Intermediate

Tiny to-do CLI app

Combine input(), a list, and a while-loop into a usable CLI app.

  1. 1Loop forever showing a menu.
  2. 2Handle add / list / quit commands.
  3. 3Persist to a file if you like.
code · python
tasks = []
while True:
    cmd = input("[a]dd / [l]ist / [q]uit: ").strip().lower()
    if cmd == "a":
        tasks.append(input("task: "))
    elif cmd == "l":
        for i, t in enumerate(tasks, 1): print(i, t)
    elif cmd == "q":
        break

Recommended

Level-up resources

Ad slot · add VITE_ADSENSE_CLIENT to activate