Wednesday, November 26, 2025

Extract pages from PDF

from PyPDF2 import PdfReader, PdfWriter


input_file =  ""    # To enter

output_file = ""    # To enter


startPage, endPage = 104, 196    # To modify


reader = PdfReader(input_file)

writer = PdfWriter()


for i in range(startPage, endPage + 1):

  writer.add_page(reader.pages[i])


with open(output_file, "wb") as f:

  writer.write(f)


print("Pages extracted successfully!")

 

Wednesday, September 24, 2025

Playing sound or audio in Python

from playsound import playsound

playsound("Sucker.mp3")



import pygame

pygame.mixer.init()

pygame.mixer.music.load(".mp3")

pygame.mixer.music.play()

while pygame.mixer.music.get_busy():

  pygame.time.Clock().tick(10)



import vlc, time

p = vlc.MediaPlayer(".mp3")

p.play()

time.sleep(0.1)

while p.is_playing():

  time.sleep(0.5)


Tuesday, September 2, 2025

Ring alarm sounds in Python

import winsound


for alias in ["SystemExit", "SystemHand"]:

  print("Playing:", alias)

  winsound.PlaySound(alias, winsound.SND_ALIAS)


for freq in range(100, 6001, 100):

  winsound.Beep(freq, 1000)

  print(f"Playing {freq} hertz")


Tuesday, August 19, 2025

ModuloQuiz

import tkinter as tk

from random import randint

import math


class ModQuiz:

  def __init__(self, root):

    self.root = root

    self.root.title("Modulo Quiz")

    self.ctr, self.num, self.den = 0, 0, 0


    self.question_label = tk.Label(root, text="", font=("Arial", 14, "bold"))

    self.question_label.pack(pady=10)


    self.answer_entry = tk.Entry(root, font=("Arial", 14, "bold"))

    self.answer_entry.pack(pady=5)

    self.answer_entry.bind("<Return>", lambda e: self.check_and_next())


    self.check_button = tk.Button(root, text="Check Answer", command=self.check_and_next, font=("Arial", 12, "bold"))

    self.check_button.pack(pady=5)


    self.result_label = tk.Label(root, text="", font=("Arial", 12, "bold"))

    self.result_label.pack(pady=5)


    self.score_label = tk.Label(root, text="Score: 0", font=("Arial", 12, "bold"))

    self.score_label.pack(pady=5)


    self.canvas = tk.Canvas(root, width=400, height=400, bg="white", highlightthickness=0)

    self.canvas.pack(pady=8)


    self.quit_button = tk.Button(root, text="Quit", command=root.destroy, font=("Arial", 12, "bold"))

    self.quit_button.pack(pady=5)


    self.ask_question()


  def ask_question(self):

    self.answer_entry.delete(0, tk.END)

    self.result_label.config(text="")

    self.num, self.den = randint(-7, 7), randint(-7, 7)

    while self.den == 0:

      self.den = randint(-7, 7)

    self.question_label.config(text=f"What is {self.num} % {self.den}?")

    self.answer_entry.focus()

    self.draw_arcs(self.den)


  def draw_arcs(self, den):

    self.canvas.delete("all")

    k = abs(den)

    pad = 20

    x0, y0, x1, y1 = 50, 40, 340, 340  # a little vertical space for labels

    cx, cy = (x0 + x1) / 2, (y0 + y1) / 2

    r = (x1 - x0) / 2 - 18

    step = 360 / k


    base = 90 # Base angle so that numbering starts at 12 o'clock


    self.canvas.create_oval(x0, y0, x1, y1, outline="black", width=1) # Draw outer circle


    for i in range(k):

      if den > 0:        # (b) Positive denominator: clockwise numbering 0..den-1

        start = base - i * step      # move clockwise by decreasing angle

        extent = -step               # draw clockwise

        label_val = i

      else:        # (c) Negative denominator: anti-clockwise numbering 0, -1, -2, ..., -(k-1)

        start = base + i * step      # move anti-clockwise by increasing angle

        extent = step                # draw anti-clockwise

        label_val = -i


      self.canvas.create_arc(x0, y0, x1, y1, start=start, extent=extent, style=tk.ARC, width=2)      # Draw arc segment


      theta_deg = start  # boundary angle      # Place label at boundary (not middle) so 0 is exactly at 12 o’clock

      theta = math.radians(theta_deg)


      r_label = r       # Slightly inside the circle for readability

      tx = cx + r_label * math.cos(theta)

      ty = cy - r_label * math.sin(theta)


      tick_in = r - 12      # Small tick mark at the boundary

      tick_out = r + 2

      tx_in = cx + tick_in * math.cos(theta)

      ty_in = cy - tick_in * math.sin(theta)

      tx_out = cx + tick_out * math.cos(theta)

      ty_out = cy - tick_out * math.sin(theta)

      self.canvas.create_line(tx_in, ty_in, tx_out, ty_out)


      tx_text = cx + (r + 40) * math.cos(theta)      # Offset text a bit towards center from the boundary

      ty_text = cy - (r + 40) * math.sin(theta)


      self.canvas.create_text(tx_text, ty_text, text=str(label_val), font=("Arial", 12, "bold"))


  def check_and_next(self):

    user_ans = self.answer_entry.get()

    try:

      if int(user_ans) == self.num % self.den:

        self.result_label.config(text="Correct!", fg="green")

        self.ctr += 1

        self.score_label.config(text=f"Score: {self.ctr}")

      else:

        self.result_label.config(text=f"Incorrect. It is {self.num % self.den}", fg="red")

    except:

      self.result_label.config(text="Please enter a valid integer.", fg="orange")

    self.root.after(1000, self.ask_question)


root = tk.Tk()

app = ModQuiz(root)

root.mainloop()

Saturday, August 2, 2025

Showing differences between contents of 2 files

with open("Bart.txt") as bart:

  L = bart.readlines()


with open("Joshua.txt") as joshua:

  L1 = joshua.readlines()


ctr = 0

for i in range(len(L)):

  if L[i] != L1[i]:

    ctr += 1

    print(L[i])  # Print differing line of File 1

    print(L1[i]) # Print differing line of File 2

    input()

print(ctr)


Thursday, March 6, 2025

Script to automatically run another script every 5 seconds

# Script to automatically run another script every 5 seconds


import subprocess, time


while True:

    subprocess.run(["python", "Just.py"])

    time.sleep(5)


Monday, January 13, 2025

Using *, **, & / with positional and keyword arguments

def add(a, *b):

  print(a)

  result = 0

  for i in b:

    result += i

  return result


print(add(1, 2, 3, 4, 5))

print()

print(add(10, 20))

print()


def func(**a):

  for k, v in a.items():

    print(k, v)


func(number=5, color="blue", fruit="apple")


def process(method, **kwargs):

  if method == "Credit Card":

    card_number = kwargs.get("card_number")

    exp_date = kwargs.get("exp_date")

    cvv = kwargs.get("cvv")

    print(f"Credit card number {card_number}")

  elif method == "Paypal":

    paypal_id = kwargs.get("paypal_id")

    print(f"PayPal ID {paypal_id}")

  elif method == "Crypto":

    wallet_address = kwargs.get("wallet_address")

    print(f"Crypto wallet {wallet_address}")

  else:

    print("Invalid payment method")


process("Credit Card", card_number="1234 5678 9012 3456", exp_date="12/25", cvv="123")

process("Paypal", paypal_id="user@example.com")

process("Crypto", wallet_address="1A2b3C4D5e6F")


def posArg(a, b, /, c, d): # Everything up to '/' must be pos. arguments

  return a + b + c + d

print(posArg(3, 4, 5, 6))

print(posArg(3, 4, 1, d=2))


def keyArg(a, b, *, c, d): # Everything after '*' must be kwargs

  return a + b + c + d

print(keyArg(3, 4, c=1, d=2))


def pos_keyArg(a, b, /, c, *, d): # Combining '/' and '*'.

  return a + b + c + d            # 'c' can be a positional or kwarg  

print(pos_keyArg(3, 4, 1, d=2))

print(pos_keyArg(3, 4, c=1, d=2))