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))

Thursday, January 9, 2025

Speech to text in Python

!pip install git+https://github.com/openai/whisper.git

!sudo apt update && sudo apt install ffmpeg


!whisper filename.mp3 --model medium.en

Sunday, January 5, 2025

Create PDF from images

from PIL import Image


images = ["Josey.jpeg", "Reena.jpeg", "Sumi.jpeg"]

pdf_path = "Output.pdf"


pdf_images = [Image.open(img).convert('RGB') for img in images]

pdf_images[0].save(pdf_path, save_all=True, append_images=pdf_images[1:])


Using * (args, kwargs, upacking, etc.) in Python

Everything * Can Be Used For In Python (Aside From Basic Math)

https://levelup.gitconnected.com/everything-can-be-used-for-in-python-aside-from-basic-math-a1c52426fc85


1) *args in Function Parameters

We can add *args in our function parameters to enable our function to take in any number of positional arguments. The * before args indicates that it will collect any number of positional arguments into a single variable. Inside the function, args is treated as a tuple.

def hello(*args):

  print(args)

hello()

hello(1)

hello(1, 2)

hello(1, 2, 3)


def hello(a, b, *args):

  print(args)

hello(1, 2)

hello(1, 2, 3)

=========================================================================

2) **kwargs in Function Parameters

Using ** instead of * allows us to take in any number of keyword arguments. Inside the function, kargs is treated as a dictionary, which stores key-value pairs.

def hello(**kargs):

  print(kargs)

hello()

hello(a=1)

hello(a=1, b=2)


def hello(a, b, **kwargs):

  print(kwargs)

hello(a=1, b=2)

hello(a=1, b=2, c=3)

=========================================================================

3) *args in Function Arguments

We can also use * to unpack an iterable into our function arguments.

L = [1, 2]

print(*L)


D = {1:'a', 2:'b'}

print(*D)


def hi(a, b, c):

  print(f"{a=} {b=} {c=}")

hi(1, 2, 3)

L = [4, 5, 6]

hi(*L)


def hi(a, b, c):

  print(f"{a=} {b=} {c=}")

hi(1, 2, 3)

=========================================================================

4) **kwargs in Function Arguments

If we use ** instead of *, we can do the same with dictionaries. Here, hi(**mydict) is the same as hi(a=4, b=5, c=6)

def hi(a, b, c):

  print(f"{a=}, {b=}, {c=}")

hi(a=4, b=5, c=6)

D = {'a':4, 'b':5, 'c':6}

hi(**D)

Similarly, we can also combine normal keyword arguments with **mydict as long as we pass all required keyword arguments into our function.

def hi(a, b, c):

  print(f"{a=}, {b=}, {c=}")

D = {'a':4, 'b':5, 'c':6}

hi(**D)

D = {'b':5, 'c':6}

hi(a=4, **D)

=========================================================================

5) Any parameter after * must be a keyword argument.

* is not placed before any parameter — this means that any parameter defined after * must be a keyword argument. In this case, c & d come after *, so c & d can only be keyword arguments. a & b can be positional or keyword arguments, but c & d must be keyword arguments. 

def hello(a, b, *, c, d):

  print(a, b, c, d)

hello(1, 2, c=3, d=4)

hello(a=1, b=2, c=3, d=4)

If we replace * alone with a / alone, this means that any function parameter defined before the / must be a positional argument.

def hello(a, b, /, c, d):

  print(a, b, c, d)

hello(1, 2, c=3, d=4)

hello(1, 2, 3, 4)

We can combine these to force additional restrictions on our function parameters.

def hola(a, b, /, c, d, *, e, f):

  print(a, b, c, d, e, f)

hola(1, 2, 3, d=4, e=5, f=6)

=========================================================================

6) *args in tuple unpacking

We can use tuple unpacking to elegantly assign multiple variables at once.

person = ['bob', 'M', 20]

name, gender, age = person

print(name, gender, age)

We can combine tuple unpacking with * if we have unused variables. If we have many more fields in person, but we only need the first 2 for now — we can use *others to assign everything else to the variable others.

person = ['bob', 'M', 20, 1.75, 70, 'black']

name, gender, *others = person

print(name, gender)

print(others)

We can switch the position of the variable with * too — in this example, we only need the first and last value, so we put *others in the middle.

person = ['bob', 'M', 20, 1.75, 70, 'black']

name, *others, hair = person

print(name, hair)

print(others)

In this example, we only need the last 2 values, so we can put *others at the front.

*others, weight, hair = person

print(weight)

print(hair)

print(others)

=========================================================================

7) Using * when combining iterables

We can also use * to combine iterables. Here, we combine 2 lists a & b by unpacking them into a list c.

a = [1, 2]

b = [3, 4]

c = [*a, *b]

print(c)

d = [[*a], [*b]]

print(d)

We can combine this technique with normal values like this:

a = [1, 2]

b = [3, 4]

c = [-1, 0, *a, *b, 5, 6]

print(c)

8) ** in combining dictionaries

** works for key-value mappings the same way * works for individual values. We can use ** to unpack dictionaries into other dictionaries in order to combine them.

x = {'a':1, 'b':2}

y = {'c':3, 'd':4}

z = {**x, **y}

print(z)


z = {**x, **y, 'e':5}

print(z)

=========================================================================

9) Importing everything from a module

We can also use from modulename import * to tell Python that we want to import everything that can be imported from some module.

from random import *

Saturday, January 4, 2025

Printing all possible outputs for randint() & randrange() functions of random module

from random import randint, randrange


arr = ['10', '30', '40', '50', '70', '90', '100']

LL = []


for i in range(1000):

  L = randrange(1, 3) # 1, 2

  U = randrange(3, 6) # 3, 4, 5

  s = ''

  for i in range(L, U+1):

    s += arr[i] + '@'

  if s not in LL:

    LL.append(s)

    #print(arr[i], end='@')

  #print()

LL.sort()

for row in LL:

  print(row)


Friday, January 3, 2025

Pandas .query() method

import pandas as pd


data = {'first name': ['Alice', 'Bob', 'Charlie', 'David'],

        'age': [25, 30, 35, 40],

        'salary': [50000, 60000, 70000, 80000]}

df = pd.DataFrame(data)


filter1 = df[(df['age'] > 30) | (df['salary'] > 60000)]

print(filter1, '\n')


filter2 = df.query('age > 30 or salary > 60000')

print(filter2, '\n')


# Using variables

Age = 30

filter3 = df.query("age > @Age")

print(filter3, '\n')


# Using backtick when column name contains space

filter4 = df.query("`first name` == 'Charlie'")

print(filter4)