Document checker

import hashlib

from difflib import SequenceMatcher

def hash_file(fileName1, fileName2):

    h2 = hashlib.sha1()

with open(fileName1, "rb") as file:

chunk = 0

while chunk != b'':

chunk = file.read(1024)

h1.update(chunk)

with open(fileName2, "rb") as file:

chunk = 0

while chunk != b'':

chunk = file.read(1024)

h2.update(chunk)

return h1.hexdigest(), h2.hexdigest()

msg1, msg2 = hash_file("pd1.pdf ", "pd1.pdf")

if(msg1 != msg2):

print("These files are not identical")

else:

print("These files are identical")


Expense Tracker

import datetime

import sqlite3

from tkcalendar import DateEntry

from tkinter import *

import tkinter.messagebox as mb

import tkinter.ttk as ttk

connector = sqlite3.connect("Expense Tracker.db")

cursor = connector.cursor()

connector.execute(

'CREATE TABLE IF NOT EXISTS ExpenseTracker (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Date DATETIME, Payee TEXT, Description TEXT, Amount FLOAT, ModeOfPayment TEXT)'

)

connector.commit()

def list_all_expenses():

global connector, table

table.delete(*table.get_children())

all_data = connector.execute('SELECT * FROM ExpenseTracker')

data = all_data.fetchall()

for values in data:

table.insert('', END, values=values)

def view_expense_details():

global table

global date, payee, desc, amnt, MoP

if not table.selection():

mb.showerror('No expense selected', 'Please select an expense from the table to view its details')

current_selected_expense = table.item(table.focus())

values = current_selected_expense['values']

expenditure_date = datetime.date(int(values[1][:4]), int(values[1][5:7]), int(values[1][8:]))

date.set_date(expenditure_date) ; payee.set(values[2]) ; desc.set(values[3]) ; amnt.set(values[4]) ; MoP.set(values[5])

def clear_fields():

global desc, payee, amnt, MoP, date, table

today_date = datetime.datetime.now().date()

desc.set('') ; payee.set('') ; amnt.set(0.0) ; MoP.set('Cash'), date.set_date(today_date)

table.selection_remove(*table.selection())

def remove_expense():

if not table.selection():

mb.showerror('No record selected!', 'Please select a record to delete!')

return

current_selected_expense = table.item(table.focus())

values_selected = current_selected_expense['values']

surety = mb.askyesno('Are you sure?', f'Are you sure that you want to delete the record of {values_selected[2]}')

if surety:

connector.execute('DELETE FROM ExpenseTracker WHERE ID=%d' % values_selected[0])

connector.commit()

list_all_expenses()

mb.showinfo('Record deleted successfully!', 'The record you wanted to delete has been deleted successfully')

def remove_all_expenses():

surety = mb.askyesno('Are you sure?', 'Are you sure that you want to delete all the expense items from the database?', icon='warning')

if surety:

table.delete(*table.get_children())

connector.execute('DELETE FROM ExpenseTracker')

connector.commit()

clear_fields()

list_all_expenses()

mb.showinfo('All Expenses deleted', 'All the expenses were successfully deleted')

else:

mb.showinfo('Ok then', 'The task was aborted and no expense was deleted!')

def add_another_expense():

global date, payee, desc, amnt, MoP

global connector

if not date.get() or not payee.get() or not desc.get() or not amnt.get() or not MoP.get():

mb.showerror('Fields empty!', "Please fill all the missing fields before pressing the add button!")

else:

connector.execute(

'INSERT INTO ExpenseTracker (Date, Payee, Description, Amount, ModeOfPayment) VALUES (?, ?, ?, ?, ?)',

(date.get_date(), payee.get(), desc.get(), amnt.get(), MoP.get())

)

connector.commit()

clear_fields()

list_all_expenses()

mb.showinfo('Expense added', 'The expense whose details you just entered has been added to the database')

def edit_expense():

global table


def edit_existing_expense():

global date, amnt, desc, payee, MoP

global connector, table

current_selected_expense = table.item(table.focus())

contents = current_selected_expense['values']


connector.execute('UPDATE ExpenseTracker SET Date = ?, Payee = ?, Description = ?, Amount = ?, ModeOfPayment = ? WHERE ID = ?',

                  (date.get_date(), payee.get(), desc.get(), amnt.get(), MoP.get(), contents[0]))

connector.commit()

clear_fields()

list_all_expenses()

mb.showinfo('Data edited', 'We have updated the data and stored in the database as you wanted')

edit_btn.destroy()

return

if not table.selection():

mb.showerror('No expense selected!', 'You have not selected any expense in the table for us to edit; please do that!')

return

view_expense_details()

edit_btn = Button(data_entry_frame, text='Edit expense', font=btn_font, width=30,

                  bg=hlb_btn_bg, command=edit_existing_expense)

edit_btn.place(x=10, y=395)

def selected_expense_to_words():

global table

if not table.selection():

mb.showerror('No expense selected!', 'Please select an expense from the table for us to read')

return

current_selected_expense = table.item(table.focus())

values = current_selected_expense['values']

message = f'Your expense can be read like: \n"You paid {values[4]} to {values[2]} for {values[3]} on {values[1]} via {values[5]}"'

mb.showinfo('Here\'s how to read your expense', message)

def expense_to_words_before_adding():

global date, desc, amnt, payee, MoP

if not date or not desc or not amnt or not payee or not MoP:

mb.showerror('Incomplete data', 'The data is incomplete, meaning fill all the fields first!')

message = f'Your expense can be read like: \n"You paid {amnt.get()} to {payee.get()} for {desc.get()} on {date.get_date()} via {MoP.get()}"'

add_question = mb.askyesno('Read your record like: ', f'{message}\n\nShould I add it to the database?')

if add_question:

add_another_expense()

else:

mb.showinfo('Ok', 'Please take your time to add this record')

dataentery_frame_bg = 'light blue'

buttons_frame_bg = 'light blue'

hlb_btn_bg = 'light pink'

lbl_font = ('Georgia', 13)

entry_font = 'Times 13 bold'

btn_font = ('Gill Sans MT', 13)

root = Tk()

root.title('Expense Tracker')

root.geometry('1200x550')

root.resizable(0, 0)

Label(root, text='EXPENSE TRACKER', font=('Noto Sans CJK TC', 15, 'bold'), bg=hlb_btn_bg).pack(side=TOP, fill=X)

desc = StringVar()

amnt = DoubleVar()

payee = StringVar()

MoP = StringVar(value='Cash')

data_entry_frame = Frame(root, bg=dataentery_frame_bg)

data_entry_frame.place(x=0, y=30, relheight=0.95, relwidth=0.25)

buttons_frame = Frame(root, bg=buttons_frame_bg)

buttons_frame.place(relx=0.25, rely=0.05, relwidth=0.75, relheight=0.21)

tree_frame = Frame(root)

tree_frame.place(relx=0.25, rely=0.26, relwidth=0.75, relheight=0.74)

Label(data_entry_frame, text='Date (M/DD/YY) :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=50)

date = DateEntry(data_entry_frame, date=datetime.datetime.now().date(), font=entry_font)

date.place(x=160, y=50)

Label(data_entry_frame, text='Payee\t             :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=230)

Entry(data_entry_frame, font=entry_font, width=31, text=payee).place(x=10, y=260)

Label(data_entry_frame, text='Description           :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=100)

Entry(data_entry_frame, font=entry_font, width=31, text=desc).place(x=10, y=130)

Label(data_entry_frame, text='Amount\t             :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=180)

Entry(data_entry_frame, font=entry_font, width=14, text=amnt).place(x=160, y=180)

Label(data_entry_frame, text='Mode of Payment:', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=310)

dd1 = OptionMenu(data_entry_frame, MoP, *['Cash', 'Cheque', 'Credit Card', 'Debit Card', 'Paytm', 'Google Pay'])

dd1.place(x=160, y=305)     ;     dd1.configure(width=10, font=entry_font)

Button(data_entry_frame, text='Add expense', command=add_another_expense, font=btn_font, width=30,

       bg=hlb_btn_bg).place(x=10, y=395)

Button(data_entry_frame, text='Convert to words before adding', font=btn_font, width=30, bg=hlb_btn_bg).place(x=10,y=450)

Button(buttons_frame, text='Delete Expense', font=btn_font, width=25, bg=hlb_btn_bg, command=remove_expense).place(x=30, y=5)

Button(buttons_frame, text='Clear Fields in DataEntry Frame', font=btn_font, width=25, bg=hlb_btn_bg,

       command=clear_fields).place(x=335, y=5)

Button(buttons_frame, text='Delete All Expenses', font=btn_font, width=25, bg=hlb_btn_bg, command=remove_all_expenses).place(x=640, y=5)

Button(buttons_frame, text='View Selected Expense\'s Details', font=btn_font, width=25, bg=hlb_btn_bg,

       command=view_expense_details).place(x=30, y=65)

Button(buttons_frame, text='Edit Selected Expense', command=edit_expense, font=btn_font, width=25, bg=hlb_btn_bg).place(x=335,y=65)

Button(buttons_frame, text='Convert Expense to a sentence', font=btn_font, width=25, bg=hlb_btn_bg,

       command=selected_expense_to_words).place(x=640, y=65)

table = ttk.Treeview(tree_frame, selectmode=BROWSE, columns=('ID', 'Date', 'Payee', 'Description', 'Amount', 'Mode of Payment'))

X_Scroller = Scrollbar(table, orient=HORIZONTAL, command=table.xview)

Y_Scroller = Scrollbar(table, orient=VERTICAL, command=table.yview)

X_Scroller.pack(side=BOTTOM, fill=X)

Y_Scroller.pack(side=RIGHT, fill=Y)

table.config(yscrollcommand=Y_Scroller.set, xscrollcommand=X_Scroller.set)

table.heading('ID', text='S No.', anchor=CENTER)

table.heading('Date', text='Date', anchor=CENTER)

table.heading('Payee', text='Payee', anchor=CENTER)

table.heading('Description', text='Description', anchor=CENTER)

table.heading('Amount', text='Amount', anchor=CENTER)

table.heading('Mode of Payment', text='Mode of Payment', anchor=CENTER)

table.column('#0', width=0, stretch=NO)

table.column('#1', width=50, stretch=NO)

table.column('#2', width=95, stretch=NO)  #Date column

table.column('#3', width=150, stretch=NO)  # Payee column

table.column('#4', width=325, stretch=NO)  # Title column

table.column('#5', width=135, stretch=NO)  # Amount column

table.column('#6', width=125, stretch=NO)  # Mode of Payment column

table.place(relx=0, y=0, relheight=1, relwidth=1)

list_all_expenses()

root.update()

root.mainloop()

Webcam Sketch

import cv2

import numpy as np

def webcam_sketch(image):

    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    img_gray_blur = cv2.GaussianBlur(img_gray, (5,5), 0)

    canny_edges = cv2.Canny(img_gray_blur, 10, 70)

    ret, mask = cv2.threshold(canny_edges, 70, 255, cv2.THRESH_BINARY_INV)

    return mask

cap = cv2.VideoCapture(0)

while True:

    ret, frame = cap.read()

    cv2.imshow('Sketch', webcam_sketch(frame))

    if cv2.waitKey(1) == 13: 

        break

cap.release()

cv2.destroyAllWindows()

controlling brightness by hand detection

import cv2

import mediapipe as mp

from math import hypot

import screen_brightness_control as sbc

import numpy as np

mpHands = mp.solutions.hands

hands = mpHands.Hands(

static_image_mode=False,

model_complexity=1,

min_detection_confidence=0.75,

min_tracking_confidence=0.75,

max_num_hands=2)

Draw = mp.solutions.drawing_utils

cap = cv2.VideoCapture(0)

while True:

_, frame = cap.read()

frame = cv2.flip(frame, 1)

frameRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

Process = hands.process(frameRGB)

landmarkList = []

if Process.multi_hand_landmarks:

for handlm in Process.multi_hand_landmarks:

for _id, landmarks in enumerate(handlm.landmark):

height, width, color_channels = frame.shape

x, y = int(landmarks.x*width), int(landmarks.y*height)

landmarkList.append([_id, x, y])

Draw.draw_landmarks(frame, handlm,

mpHands.HAND_CONNECTIONS)

if landmarkList != []:

x_1, y_1 = landmarkList[4][1], landmarkList[4][2]

x_2, y_2 = landmarkList[8][1], landmarkList[8][2]

cv2.circle(frame, (x_1, y_1), 7, (0, 255, 0), cv2.FILLED)

cv2.circle(frame, (x_2, y_2), 7, (0, 255, 0), cv2.FILLED)

cv2.line(frame, (x_1, y_1), (x_2, y_2), (0, 255, 0), 3)

L = hypot(x_2-x_1, y_2-y_1)

b_level = np.interp(L, [15, 220], [0, 100])

sbc.set_brightness(int(b_level))

cv2.imshow('Image', frame)

if cv2.waitKey(1) & 0xff == ord('q'):

break


Youtube video downloader

import tkinter as tk

from tkinter import *

from pytube import YouTube

from tkinter import messagebox, filedialog

def Widgets():

head_label = Label(root, text="YouTube Video Downloader",

padx=15,

pady=15,

font="SegoeUI 14",

bg="palegreen",

fg="black")

head_label.grid(row=1,

column=1,

pady=10,

padx=5,

columnspan=3)

link_label = Label(root,

text="YouTube link :",

bg="salmon",

pady=5,

padx=5)

link_label.grid(row=2,

column=0,

pady=5,

padx=5)

root.linkText = Entry(root,

width=35,

textvariable=video_Link,

font="Arial 14")

root.linkText.grid(row=2,

column=1,

pady=5,

padx=5,

columnspan=2)

destination_label = Label(root,

text="Destination :",

bg="salmon",

pady=5,

padx=9)

destination_label.grid(row=3,

column=0,

pady=5,

padx=5)

root.destinationText = Entry(root,

width=27,

textvariable=download_Path,

font="Arial 14")

root.destinationText.grid(row=3,

column=1,

pady=5,

padx=5)

browse_B = Button(root,

text="Browse",

command=Browse,

width=10,

bg="bisque",

relief=GROOVE)

browse_B.grid(row=3,

column=2,

pady=1,

padx=1)

Download_B = Button(root,

text="Download Video",

command=Download,

width=20,

bg="thistle1",

pady=10,

padx=15,

relief=GROOVE,

font="Georgia, 13")

Download_B.grid(row=4,

column=1,

pady=20,

padx=20)

def Browse():

download_Directory = filedialog.askdirectory(

initialdir="YOUR DIRECTORY PATH", title="Save Video")

download_Path.set(download_Directory)

def Download():

Youtube_link = video_Link.get()

download_Folder = download_Path.get()

getVideo = YouTube(Youtube_link)

videoStream = getVideo.streams.first()

videoStream.download(download_Folder)

messagebox.showinfo("SUCCESSFULLY",

"DOWNLOADED AND SAVED IN\n"

+ download_Folder)

root = tk.Tk()

root.geometry("520x280")

root.resizable(False, False)

root.title("YouTube Video Downloader")

root.config(background="light blue")

video_Link = StringVar()

download_Path = StringVar()

Widgets()

root.mainloop()


Counting Fingers

import cv2

import mediapipe as mp

cap = cv2.VideoCapture(0)

mp_Hands = mp.solutions.hands

hands = mp_Hands.Hands()

mpdraw = mp.solutions.drawing_utils

finger_Coord = [(8, 6), (12, 10), (16, 14), (20, 18)]

thumb_Coord = (4,2)

while True:

    success, image = cap.read()

    RGB_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    results = hands.process(RGB_image)

    multiLandMarks = results.multi_hand_landmarks

    if multiLandMarks:

        handList = []

        for handLms in multiLandMarks:

            mpdraw.draw_landmarks(image, handLms, mp_Hands.HAND_CONNECTIONS)

            for idx, lm in enumerate(handLms.landmark):

                h, w, c = image.shape

                cx, cy = int(lm.x * w), int(lm.y * h)

                handList.append((cx, cy))

            for point in handList:

                cv2.circle(image, point, 10, (255, 255, 0), cv2.FILLED)

                upCount = 0

        for coordinate in finger_Coord:

            if handList[coordinate[0]][1] < handList[coordinate[1]][1]:

                upCount += 1

        if handList[thumb_Coord[0]][0] > handList[thumb_Coord[1]][0]:

            upCount += 1

            cv2.putText(image, str(upCount), (150,150), cv2.FONT_HERSHEY_PLAIN, 12, (0,255,0), 12)


    cv2.imshow("Counting number of fingers", image)

    cv2.waitKey(1)

sudoku

board=[

    [2,3,0,0,7,0,0,0,0],

    [6,0,0,1,9,5,0,0,0],

    [0,9,8,0,0,0,0,6,0],

    [8,0,0,0,6,0,0,0,3],

    [4,0,0,8,0,3,0,0,1],

    [5,0,0,0,2,0,0,0,6],

    [0,6,0,0,0,0,2,8,0],

    [0,0,0,4,1,9,0,0,5],

    [0,0,0,0,9,0,0,8,9]]

def print_board(bo):

    for i in range(len(bo)):

        if i%3 == 0 and i!=0:

            print("---------------------")

        for j in range(len(bo[0])):

            if j%3 == 0 and j!=0:

                print(" | ", end ="")

            if j==8:

                print(bo[i][j])

            else:

                print(str(bo[i][j]) + " ",end="")

def find_empty(bo):

    for i in range(len(bo)):

        for j in range(len(bo[0])):

            if bo[i][j] == 0:

                return (i, j)

    return None

def valid(bo, num, pos):

    for i in range(len(bo[0])):

        if bo[pos[0]][i] == num and pos[1]!= i:

            return False

    for j in range(len(bo)):

        if bo[i][pos[1]] == num and pos[0]!= i:

            return False

    box_x = pos[1]//3

    box_y = pos[0]//3

    for i in range(box_y*3, box_y*3 + 3):

        for j in range(box_x*3, box_x*3 + 3):

            if bo[i][j] == num and  (i,j) != pos:

                return False

    return True

def solve(bo):

    find = find_empty(bo)

    if not find:

        return True

    else:

        row, col = find

    for i in range(1,10):

        if valid(bo, i , (row,col)):

            bo[row][col] = i

            if solve(bo):

                return True

            bo[row][col]=0

    return False

print_board(board)

solve(board)

print("Solving")

print_board(board)

print("Solved")

snowman

import turtle

turtle.speed(2)

turtle.setup(800, 700)

turtle.bgcolor("black")

turtle.penup()

turtle.goto(0, -320)

turtle.pendown()

turtle.color("#c1f8b5")

turtle.begin_fill()

turtle.circle(320)

turtle.end_fill()

turtle.penup()

turtle.goto(0, -280)

turtle.pendown()

turtle.color("white")

turtle.begin_fill()

turtle.circle(110)

turtle.end_fill()

turtle.penup()

turtle.goto(0, -110)

turtle.pendown()

turtle.begin_fill()

turtle.circle(90)

turtle.end_fill()

turtle.penup()

turtle.goto(0, 20)

turtle.pendown()

turtle.begin_fill()

turtle.circle(70)

turtle.end_fill()

def black_circle():

turtle.color("black")

turtle.begin_fill()

turtle.circle(10)

turtle.end_fill()

x = -20

for i in range(2):

turtle.penup()

turtle.goto(x, 110)

turtle.pendown()

black_circle()

x = x + 40

y = 0

for i in range(5):

turtle.penup()

turtle.goto(0, y)

turtle.pendown()

black_circle()

y = y - 55

turtle.penup()

turtle.goto(0,70)

turtle.pendown()

turtle.color("red")

turtle.begin_fill()

turtle.circle(17)

turtle.end_fill()

turtle.penup()

turtle.goto(0,75)

turtle.pendown()

turtle.color("white")

turtle.begin_fill()

turtle.circle(17)

turtle.end_fill()

turtle.penup()

turtle.goto(75, 0)

turtle.pendown()

turtle.color("brown")

turtle.begin_fill()

turtle.left(40)

for i in range(2):

turtle.forward(75)

turtle.left(90)

turtle.forward(7)

turtle.left(90)

turtle.end_fill()

turtle.penup()

turtle.goto(115, 38)

turtle.pendown()

turtle.begin_fill()

turtle.left(40)

for i in range(2):

turtle.forward(25)

turtle.left(90)

turtle.forward(5)

turtle.left(90)

turtle.end_fill()

turtle.begin_fill()

turtle.right(100)

for i in range(2):

turtle.forward(25)

turtle.left(90)

turtle.forward(5)

turtle.left(90)

turtle.end_fill()

turtle.penup()

turtle.goto(-130, 50)

turtle.pendown()

turtle.begin_fill()

turtle.right(10)

for i in range(2):

turtle.forward(75)

turtle.right(90)

turtle.forward(7)

turtle.right(90)

turtle.end_fill()

turtle.penup()

turtle.goto(-112, 58)

turtle.pendown()

turtle.begin_fill()

turtle.right(40)

for i in range(2):

turtle.forward(25)

turtle.right(90)

turtle.forward(5)

turtle.right(90)

turtle.end_fill()

turtle.begin_fill()

turtle.right(100)

turtle.penup()

turtle.goto(-108, 31)

turtle.pendown()

for i in range(2):

turtle.forward(25)

turtle.right(90)

turtle.forward(5)

turtle.right(90)

turtle.end_fill()

turtle.penup()

turtle.goto(50, 150)

turtle.pendown()

turtle.color("black")

turtle.begin_fill()

turtle.right(10)

turtle.forward(100)

turtle.right(90)

turtle.forward(10)

turtle.right(90)

turtle.forward(20)

turtle.left(90)

turtle.forward(45)

turtle.right(90)

turtle.forward(60)

turtle.right(90)

turtle.forward(45)

turtle.left(90)

turtle.forward(20)

turtle.right(90)

turtle.end_fill()

turtle.hideturtle()


Extract Links

import requests

from bs4 import BeautifulSoup

url = 'https://www.pythonforengineers.in/'

reqs = requests.get(url)

soup = BeautifulSoup(reqs.text, 'html.parser')

urls = []

for link in soup.find_all('a'):

print(link.get('href'))


Scraping TV Rating

import requests

from bs4 import BeautifulSoup

def getdata(url):

r = requests.get(url)

return r.text

htmldata = getdata("https://barcindia.co.in/data-insights")

soup = BeautifulSoup(htmldata, 'html.parser')

data = ''

for i in soup.find_all('tbody'):

data = data + (i.get_text())

data

data = ''.join((filter(lambda i: i not in ['\t'], data)))

print(data)


Caller Info

import requests

import pandas as pd

from bs4 import BeautifulSoup

def getdata(url):

r=requests.get(url)

return r.text

# Enter your own API key 

api = 'YOUR API KEY'

number = '9876543210'

country = 'IN'

# pass Your API, number and country code

htmldata=getdata('http://apilayer.net/api/validate?access_key='+api+'&number='+number+'&country_code='+country+'&format=1')

soup = BeautifulSoup(htmldata, 'html.parser')

print(soup)


Digital clock

import time

import datetime as dt

import turtle

t = turtle.Turtle()

t1 = turtle.Turtle()

s = turtle.Screen()

s.bgcolor("green")

sec = dt.datetime.now().second

min = dt.datetime.now().minute

hr = dt.datetime.now().hour

t1.pensize(3)

t1.color('black')

t1.penup()

t1.goto(-20, 0)

t1.pendown()

for i in range(2):

t1.forward(200)

t1.left(90)

t1.forward(70)

t1.left(90)

t1.hideturtle()

while True:

t.hideturtle()

t.clear()

t.write(str(hr).zfill(2)

+ ":"+str(min).zfill(2)+":"

+ str(sec).zfill(2),

font=("Arial Narrow", 35, "bold"))

time.sleep(1)

sec += 1

if sec == 60:

sec = 0

min += 1

if min == 60:

min = 0

hr += 1

if hr == 13:

hr = 1


openai

import openai

openai.api_key = "your secret api key"

while True:

    model_engine = "text-davinci-003"

    prompt = input('Enter new prompt: ')

    if 'exit' in prompt or 'quit' in prompt:

        break

    completion = openai.Completion.create(

        engine=model_engine,

        prompt=prompt,

        max_tokens=1024,

        n=1,

        stop=None,

        temperature=0.5,

    )

    response = completion.choices[0].text

    print(response)


To get secret api key  go to   openai.com/api/ and signup

then login and go to  platform.openai.com/ 

click on personal and then click on vie api keys and now click on 'create new secret key'.

Scientific calculator

import tkinter as tk

from math import *

convert_constant = 1

inverse_convert_constant = 1

btn_params = {'padx': 16, 'pady': 1, 'bd': 4, 'fg': 'white', 'bg': 'black', 'font': ('arial', 18),

              'width': 2, 'height': 2, 'relief': 'flat', 'activebackground': "black"}

def fsin(arg):

    return sin(arg * convert_constant)

def fcos(arg):

    return cos(arg * convert_constant)

def ftan(arg):

    return tan(arg * convert_constant)

def arcsin(arg):

    return inverse_convert_constant * (asin(arg))

def arccos(arg):

    return inverse_convert_constant * (acos(arg))

def arctan(arg):

    return inverse_convert_constant * (atan(arg))

class Calculator:

    def __init__(self, master):

        self.expression = ""

        self.recall = ""

        self.sum_up = ""

        self.text_input = tk.StringVar()

        self.master = master

        top_frame = tk.Frame(master, width=650, height=10,

                             bd=10, relief='flat', bg='gray')

        top_frame.pack(side=tk.TOP)

        bottom_frame = tk.Frame(

            master, width=650, height=470, bd=2, relief='flat', bg='black')

        bottom_frame.pack(side=tk.BOTTOM)

        txt_display = tk.Entry(top_frame, font=('arial', 36), relief='flat', bg='black', fg='white', textvariable=self.text_input, width=60, bd=12, justify='right')

        txt_display.pack()

        self.btn_left_brack = tk.Button(

            bottom_frame, **btn_params, text="(", border=1, command=lambda: self.btn_click('('))

        self.btn_left_brack.grid(row=0, column=0)

        self.btn_right_brack = tk.Button(

            bottom_frame, **btn_params, text=")", command=lambda: self.btn_click(')'))

        self.btn_right_brack.grid(row=0, column=1)

        self.btn_exp = tk.Button(

            bottom_frame, **btn_params, text="exp", command=lambda: self.btn_click('exp('))

        self.btn_exp.grid(row=0, column=2)

        self.btn_pi = tk.Button(

            bottom_frame, **btn_params, text="Ï€", command=lambda: self.btn_click('pi'))

        self.btn_pi.grid(row=0, column=3)

        self.btn_sqrt = tk.Button(

            bottom_frame, **btn_params, text="sqrt", command=lambda: self.btn_click('sqrt('))

        self.btn_sqrt.grid(row=0, column=4)

        self.btn_clear = tk.Button(

            bottom_frame, **btn_params, text="C", command=self.btn_clear_all)

        self.btn_clear.grid(row=0, column=5)

        self.btn_del = tk.Button(

            bottom_frame, **btn_params, text="AC", command=self.btn_clear1)

        self.btn_del.grid(row=0, column=6)

        self.btn_change_sign = tk.Button(

            bottom_frame, **btn_params, text="+/-", command=self.change_signs)

        self.btn_change_sign.grid(row=0, column=7)

        self.btn_div = tk.Button(

            bottom_frame, **btn_params, text="/", command=lambda: self.btn_click('/'))

        self.btn_div.grid(row=0, column=8)

        self.btn_Deg = tk.Button(bottom_frame, **btn_params, activeforeground='gray', text="Deg", command=self.convert_deg)

        self.btn_Deg.grid(row=1, column=0)

        self.btn_Rad = tk.Button(bottom_frame, **btn_params, foreground='white', activeforeground='Gray', text="Rad", command=self.convert_rad)

        self.btn_Rad.grid(row=1, column=1)

        self.cube = tk.Button(bottom_frame, **btn_params, text=u"x\u00B3", command=lambda: self.btn_click('**3'))

        self.cube.grid(row=1, column=2)

        self.btn_abs = tk.Button(

            bottom_frame, **btn_params, text="abs", command=lambda: self.btn_click('abs' + '('))

        self.btn_abs.grid(row=1, column=3)

        self.btn_MC = tk.Button(

            bottom_frame, **btn_params, text="MC", command=self.memory_clear)

        self.btn_MC.grid(row=1, column=4)

        self.btn_7 = tk.Button(bottom_frame, **btn_params, text="7", command=lambda: self.btn_click(7))

        self.btn_7.configure(activebackground="black", bg='black')

        self.btn_7.grid(row=1, column=5)

        self.btn_8 = tk.Button(bottom_frame, **btn_params, text="8", command=lambda: self.btn_click(8))

        self.btn_8.configure(activebackground="black", bg='black')

        self.btn_8.grid(row=1, column=6)

        self.btn_9 = tk.Button(bottom_frame, **btn_params, text="9", command=lambda: self.btn_click(9))

        self.btn_9.configure(activebackground="black", bg='black')

        self.btn_9.grid(row=1, column=7)

        self.btn_mult = tk.Button(bottom_frame, **btn_params, text="x", command=lambda: self.btn_click('*'))

        self.btn_mult.grid(row=1, column=8)

        self.btn_sin = tk.Button(

            bottom_frame, **btn_params, text="sin", command=lambda: self.btn_click('fsin('))

        self.btn_sin.grid(row=2, column=0)

        self.btn_cos = tk.Button(

            bottom_frame, **btn_params, text="cos", command=lambda: self.btn_click('fcos('))

        self.btn_cos.grid(row=2, column=1)

        self.btn_tan = tk.Button(bottom_frame, **btn_params, text="tan", command=lambda: self.btn_click('ftan('))

        self.btn_tan.grid(row=2, column=2)

        self.btn_log = tk.Button(bottom_frame, **btn_params, text="log", command=lambda: self.btn_click('log('))

        self.btn_log.grid(row=2, column=3)

        self.btn_MR = tk.Button(bottom_frame, **btn_params, text="MR", command=self.memory_recall)

        self.btn_MR.grid(row=2, column=4)

        self.btn_4 = tk.Button(bottom_frame, **btn_params, text="4", command=lambda: self.btn_click(4))

        self.btn_4.configure(activebackground="black", bg='black')

        self.btn_4.grid(row=2, column=5)

        self.btn_5 = tk.Button(bottom_frame, **btn_params, text="5", command=lambda: self.btn_click(5))

        self.btn_5.configure(activebackground="black", bg='black')

        self.btn_5.grid(row=2, column=6)

        self.btn_6 = tk.Button(bottom_frame, **btn_params, text="6", command=lambda: self.btn_click(6))

        self.btn_6.configure(activebackground="black", bg='black')

        self.btn_6.grid(row=2, column=7)

        self.btnSub = tk.Button(bottom_frame, **btn_params, text="-", command=lambda: self.btn_click('-'))

        self.btnSub.grid(row=2, column=8)

        self.btn_sin_inverse = tk.Button(bottom_frame, **btn_params, text=u"sin-\u00B9", command=lambda: self.btn_click('arcsin('))

        self.btn_sin_inverse.grid(row=3, column=0)

        self.btn_cos_inverse = tk.Button(bottom_frame, **btn_params, text=u"cos-\u00B9", command=lambda: self.btn_click('arccos('))

        self.btn_cos_inverse.grid(row=3, column=1)

        self.btn_tan_inverse = tk.Button(bottom_frame, **btn_params, text=u"tan-\u00B9", command=lambda: self.btn_click('arctan('))

        self.btn_tan_inverse.grid(row=3, column=2)

        self.btn_ln = tk.Button(bottom_frame, **btn_params, text="ln", command=lambda: self.btn_click('log1p('))

        self.btn_ln.grid(row=3, column=3)

        self.btn_M_plus = tk.Button(bottom_frame, **btn_params, text="M+", command=self.memory_add)

        self.btn_M_plus.grid(row=3, column=4)

        self.btn_1 = tk.Button(bottom_frame, **btn_params, text="1", command=lambda: self.btn_click(1))

        self.btn_1.configure(activebackground="black", bg='black')

        self.btn_1.grid(row=3, column=5)

        self.btn_2 = tk.Button(bottom_frame, **btn_params, text="2", command=lambda: self.btn_click(2))

        self.btn_2.configure(activebackground="black", bg='black')

        self.btn_2.grid(row=3, column=6)

        self.btn_3 = tk.Button(bottom_frame, **btn_params, text="3", command=lambda: self.btn_click(3))

        self.btn_3.configure(activebackground="black", bg='black')

        self.btn_3.grid(row=3, column=7)

        self.btn_add = tk.Button(

            bottom_frame, **btn_params, text="+", command=lambda: self.btn_click('+'))

        self.btn_add.grid(row=3, column=8)

        self.btn_fact = tk.Button(bottom_frame, **btn_params, text="n!", command=lambda: self.btn_click('factorial('))

        self.btn_fact.grid(row=4, column=0)

        self.btn_sqr = tk.Button(bottom_frame, **btn_params, text=u"x\u00B2", command=lambda: self.btn_click('**2'))

        self.btn_sqr.grid(row=4, column=1)

        self.btn_power = tk.Button(bottom_frame, **btn_params, text="x^y", command=lambda: self.btn_click('**'))

        self.btn_power.grid(row=4, column=2)

        self.btn_ans = tk.Button(bottom_frame, **btn_params, text="ans", command=self.answer)

        self.btn_ans.grid(row=4, column=3)

        self.btn_comma = tk.Button(bottom_frame, **btn_params, text=",", command=lambda: self.btn_click(','))

        self.btn_comma.grid(row=4, column=4)

        self.btn_0 = tk.Button(bottom_frame, **btn_params, text="0", command=lambda: self.btn_click(0))

        self.btn_0.configure(activebackground="black", bg='black', width=7, bd=5)

        self.btn_0.grid(row=4, column=5, columnspan=2)

        self.btn_eq = tk.Button(bottom_frame, **btn_params, text="=", command=self.btn_equal)

        self.btn_eq.configure(bg='Gray', activebackground='#009999')

        self.btn_eq.grid(row=4, column=7)

        self.btn_dec = tk.Button(bottom_frame, **btn_params, text=".", command=lambda: self.btn_click('.'))

        self.btn_dec.grid(row=4, column=8)

    def btn_click(self, expression_val):

        if len(self.expression) >= 23:

            self.expression = self.expression

            self.text_input.set(self.expression)

        else:

            self.expression = self.expression + str(expression_val)

            self.text_input.set(self.expression)

    def btn_clear1(self):

        self.expression = self.expression[:-1]

        self.text_input.set(self.expression)

    def change_signs(self):

        self.expression = self.expression + '-'

        self.text_input.set(self.expression) 

    def memory_clear(self):

        self.recall = "" 

    def memory_add(self):

        self.recall = self.recall + '+' + self.expression 

    def answer(self):

        self.answer = self.sum_up

        self.expression = self.expression + self.answer

        self.text_input.set(self.expression)

    def memory_recall(self):

        if self.expression == "":

            self.text_input.set('0' + self.expression + self.recall)

        else:

            self.text_input.set(self.expression + self.recall) 

    def convert_deg(self):

        global convert_constant

        global inverse_convert_constant

        convert_constant = pi / 180

        inverse_convert_constant = 180 / pi

        self.btn_Rad["foreground"] = 'white'

        self.btn_Deg["foreground"] = 'RED'

    def convert_rad(self):

        global convert_constant

        global inverse_convert_constant

        convert_constant = 1

        inverse_convert_constant = 1

        self.btn_Rad["foreground"] = 'RED'

        self.btn_Deg["foreground"] = 'white' 

    def btn_clear_all(self):

        self.expression = ""

        self.text_input.set("") 

    def btn_equal(self):

        self.sum_up = str(eval(self.expression))

        self.text_input.set(self.sum_up)

        self.expression = self.sum_up

root = tk.Tk()

b = Calculator(root)

root.title("Scientific Calculator!")

root.geometry("650x490+50+50")

root.resizable(False, False)

root.mainloop()

music player

import pygame

from pygame import mixer

pygame.init()

mixer.init()

screen = pygame.display.set_mode((600, 400))

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

mixer.music.play()

print("Press 'p' to pause 'r' to resume")

print("Press 'q' to quit")

running = True

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_p:

                mixer.music.pause()

            if event.key == pygame.K_r:

                mixer.music.unpause()

            if event.key == pygame.K_q:

                running = False

quit()

Voice Assistant

import pyttsx3

import speech_recognition as sr

def take_commands():

    r = sr.Recognizer()

    with sr.Microphone() as source:

        print('Listening')

        r.pause_threshold = 0.7

        audio = r.listen(source)

        try:

            print("Recognizing")

            Query = r.recognize_google(audio)

            print("the query is printed='", Query, "'")

        except Exception as e:

            print(e)

            print("Say that again sir")

            return "None"

    return Query

def Speak(audio):

    engine = pyttsx3.init()

    engine.say(audio)

    engine.runAndWait()

if __name__ == '__main__':

    while True:

        command = take_commands()

        if "exit" in command:

            Speak("Sure sir! as your wish, bye")

            break

        if "welcome" in command:

            Speak("hi welcome to python for engineers")

        if "python" in command:

            Speak("a complete solution for python programming")

Typing Speed Test Application

from tkinter import *

import ctypes

import random

import tkinter

ctypes.windll.shcore.SetProcessDpiAwareness(1)

storage = Tk()

storage.title('Typing Speed Test')

storage.geometry('1400x700')

storage.option_add("*Label.Font", "consolas 30")

storage.option_add("*Button.Font", "consolas 30")

def handlingLabels():

    random_selection = [

        'Software engineering is the branch of computer science that deals with the design, development, testing, and maintenance of software applications. Software engineers apply engineering principles and knowledge of programming languages to build software solutions for end users.',

        'A web developer is a programmer who develops World Wide Web applications using a client–server model. The applications typically use HTML, CSS, and JavaScript in the client, and any general-purpose programming language in the server. HTTP is used for communications between client and server.'

    ]

    text = random.choice(random_selection).lower()

    splitPoint = 0

    global nameLabelLeft

    nameLabelLeft = Label(storage, text=text[0:splitPoint], fg='green')

    nameLabelLeft.place(relx=0.5, rely=0.5, anchor=E)

    global nameLabelRight

    nameLabelRight = Label(storage, text=text[splitPoint:])

    nameLabelRight.place(relx=0.5, rely=0.5, anchor=W)

    global currentAlphabetLabel

    currentAlphabetLabel = Label(storage, text=text[splitPoint], fg='grey')

    currentAlphabetLabel.place(relx=0.5, rely=0.6, anchor=N)

    global secondsLeft

    headingLabel = Label(storage, text=f'CopyAssignment - Typing Speed Test', fg='blue')

    headingLabel.place(relx=0.5, rely=0.2, anchor=S)

    secondsLeft = Label(storage, text=f'0 Seconds', fg='red')

    secondsLeft.place(relx=0.5, rely=0.4, anchor=S)

    global writeAble

    writeAble = True

    storage.bind('<Key>', handlekeyPress)

    global secondsPassed

    secondsPassed = 0

    storage.after(60000, stopGame)

    storage.after(1000, timeAddition)

def stopGame():

    global writeAble

    writeAble = False

    amountWords = len(nameLabelLeft.cget('text').split(' '))

    secondsLeft.destroy()

    currentAlphabetLabel.destroy()

    nameLabelRight.destroy()

    nameLabelLeft.destroy()

    global labelOfResult

    labelOfResult = Label(storage, text=f'Words per Minute (WPM): {amountWords}', fg='black')

    labelOfResult.place(relx=0.5, rely=0.4, anchor=CENTER)

    global showcaseResults

    showcaseResults = Button(storage, text=f'Retry', command=restartGame)

    showcaseResults.place(relx=0.5, rely=0.6, anchor=CENTER)

def restartGame():

    labelOfResult.destroy()

    showcaseResults.destroy()

    handlingLabels()

def timeAddition():

    global secondsPassed

    secondsPassed += 1

    secondsLeft.configure(text=f'{secondsPassed} Seconds')

    if writeAble:

        storage.after(1000, timeAddition)

def handlekeyPress(event=None):

    try:

        if event.char.lower() == nameLabelRight.cget('text')[0].lower():

            nameLabelRight.configure(text=nameLabelRight.cget('text')[1:])

            nameLabelLeft.configure(text=nameLabelLeft.cget('text') + event.char.lower())

            currentAlphabetLabel.configure(text=nameLabelRight.cget('text')[0])

    except tkinter.TclError:

        pass

handlingLabels()

storage.mainloop()


Open Games Con



 Open Games Con

(The Main Gaming,Art, Tech And Blockchain Event In Europe) 

 Zaragoza, Spain 2023 July, 21-22-23th

Brochure

Drawing Application

from tkinter import *

from tkinter.ttk import Scale

from tkinter import colorchooser,filedialog,messagebox

import PIL.ImageGrab as ImageGrab

class Draw():

    def __init__(self,root):

        self.root =root

        self.root.title("Painter")

        self.root.configure(background="white")

        self.pointer= "black"

        self.erase="white"    

        text=Text(root)

        text.tag_configure("tag_name", justify='center', font=('arial',25),background='#292826',foreground='orange')

        text.insert("1.0", "Drawing Application ")

        text.tag_add("tag_name", "1.0", "end")

        text.pack()

        self.pick_color = LabelFrame(self.root,text='Colors',font =('arial',15),bd=5,relief=RIDGE,bg="white")

        self.pick_color.place(x=0,y=40,width=90,height=185)

        colors = ['blue','red','green', 'orange','violet','black','yellow','purple','pink','gold','brown','indigo']

        i=j=0

        for color in colors:

            Button(self.pick_color,bg=color,bd=2,relief=RIDGE,width=3,command=lambda col=color:self.select_color(col)).grid(row=i,column=j)

            i+=1

            if i==6:

                i=0

                j=1

        self.eraser_btn= Button(self.root,text="Eraser",bd=4,bg='white',command=self.eraser,width=9,relief=RIDGE)

        self.eraser_btn.place(x=0,y=197)

        self.clear_screen= Button(self.root,text="Clear Screen",bd=4,bg='white',command= lambda : self.background.delete('all'),width=9,relief=RIDGE)

        self.clear_screen.place(x=0,y=227)

        self.save_btn= Button(self.root,text="ScreenShot",bd=4,bg='white',command=self.save_drawing,width=9,relief=RIDGE)

        self.save_btn.place(x=0,y=257)

        self.bg_btn= Button(self.root,text="Background",bd=4,bg='white',command=self.canvas_color,width=9,relief=RIDGE)

        self.bg_btn.place(x=0,y=287)

        self.pointer_frame= LabelFrame(self.root,text='size',bd=5,bg='white',font=('arial',15,'bold'),relief=RIDGE)

        self.pointer_frame.place(x=0,y=320,height=200,width=70)

        self.pointer_size =Scale(self.pointer_frame,orient=VERTICAL,from_ =48 , to =0, length=168)

        self.pointer_size.set(1)

        self.pointer_size.grid(row=0,column=1,padx=15)

        self.background = Canvas(self.root,bg='white',bd=5,relief=GROOVE,height=470,width=680)

        self.background.place(x=80,y=40)

        self.background.bind("<B1-Motion>",self.paint) 

    def paint(self,event):       

        x1,y1 = (event.x-2), (event.y-2)  

        x2,y2 = (event.x+2), (event.y+2)  

        self.background.create_oval(x1,y1,x2,y2,fill=self.pointer,outline=self.pointer,width=self.pointer_size.get())

    def select_color(self,col):

        self.pointer = col

    def eraser(self):

        self.pointer= self.erase

    def canvas_color(self):

        color=colorchooser.askcolor()

        self.background.configure(background=color[1])

        self.erase= color[1]

    def save_drawing(self):

        try:

            file_ss =filedialog.asksaveasfilename(defaultextension='jpg')

            x=self.root.winfo_rootx() + self.background.winfo_x()

            y=self.root.winfo_rooty() + self.background.winfo_y()

            x1= x + self.background.winfo_width() 

            y1= y + self.background.winfo_height()

            ImageGrab.grab().crop((x , y, x1, y1)).save(file_ss)

            messagebox.showinfo('Screenshot Successfully Saved as' + str(file_ss))

        except:

            print("Error in saving the screenshot")

if __name__ =="__main__":

    root = Tk()

    p= Draw(root)

    root.mainloop()

Fire detection

import cv2

import numpy as np

import matplotlib.pyplot as plt

live_camera = cv2.VideoCapture(0)

while(live_camera.isOpened()):

    ret, frame = live_camera.read()

    cv2.imshow("Fire Detection",frame)

    if cv2.waitKey(10) == 27:

        break

img_RGB = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

img_cap = plt.imshow(img_RGB)

plt.show()

live_camera.release()

cv2.destroyAllWindows()


Notepad

import tkinter

import os

from tkinter import *

from tkinter.messagebox import *

from tkinter.filedialog import *

class Notepad:

__root = Tk()

__thisWidth = 300

__thisHeight = 300

__thisTextArea = Text(__root)

__thisMenuBar = Menu(__root)

__thisFileMenu = Menu(__thisMenuBar, tearoff=0)

__thisEditMenu = Menu(__thisMenuBar, tearoff=0)

__thisHelpMenu = Menu(__thisMenuBar, tearoff=0)

__thisScrollBar = Scrollbar(__thisTextArea)

__file = None

def __init__(self,**kwargs):

try:

self.__root.wm_iconbitmap("Notepad.ico")

except:

pass

try:

self.__thisWidth = kwargs['width']

except KeyError:

pass

try:

self.__thisHeight = kwargs['height']

except KeyError:

pass

self.__root.title("Untitled - Notepad")

screenWidth = self.__root.winfo_screenwidth()

screenHeight = self.__root.winfo_screenheight()

left = (screenWidth / 2) - (self.__thisWidth / 2)

top = (screenHeight / 2) - (self.__thisHeight /2)

self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth,

self.__thisHeight,

left, top))

self.__root.grid_rowconfigure(0, weight=1)

self.__root.grid_columnconfigure(0, weight=1)

self.__thisTextArea.grid(sticky = N + E + S + W)

self.__thisFileMenu.add_command(label="New",

command=self.__newFile)

self.__thisFileMenu.add_command(label="Open",

command=self.__openFile)

self.__thisFileMenu.add_command(label="Save",

command=self.__saveFile)

self.__thisFileMenu.add_separator()

self.__thisFileMenu.add_command(label="Exit",

command=self.__quitApplication)

self.__thisMenuBar.add_cascade(label="File",

menu=self.__thisFileMenu)

self.__thisEditMenu.add_command(label="Cut",

command=self.__cut)

self.__thisEditMenu.add_command(label="Copy",

command=self.__copy)

self.__thisEditMenu.add_command(label="Paste",

command=self.__paste)

self.__thisMenuBar.add_cascade(label="Edit",

menu=self.__thisEditMenu)

self.__thisHelpMenu.add_command(label="About Notepad",

command=self.__showAbout)

self.__thisMenuBar.add_cascade(label="Help",

menu=self.__thisHelpMenu)

self.__root.config(menu=self.__thisMenuBar)

self.__thisScrollBar.pack(side=RIGHT,fill=Y)

self.__thisScrollBar.config(command=self.__thisTextArea.yview)

self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)

def __quitApplication(self):

self.__root.destroy()

def __showAbout(self):

showinfo("Notepad","Mrinal Verma")

def __openFile(self):

self.__file = askopenfilename(defaultextension=".txt",

filetypes=[("All Files","*.*"),

("Text Documents","*.txt")])

if self.__file == "":

self.__file = None

else:

self.__root.title(os.path.basename(self.__file) + " - Notepad")

self.__thisTextArea.delete(1.0,END)

file = open(self.__file,"r")

self.__thisTextArea.insert(1.0,file.read())

file.close()

def __newFile(self):

self.__root.title("Untitled - Notepad")

self.__file = None

self.__thisTextArea.delete(1.0,END)

def __saveFile(self):

if self.__file == None:

self.__file = asksaveasfilename(initialfile='Untitled.txt',

defaultextension=".txt",

filetypes=[("All Files","*.*"),

("Text Documents","*.txt")])

if self.__file == "":

self.__file = None

else:

file = open(self.__file,"w")

file.write(self.__thisTextArea.get(1.0,END))

file.close()

self.__root.title(os.path.basename(self.__file) + " - Notepad")

else:

file = open(self.__file,"w")

file.write(self.__thisTextArea.get(1.0,END))

file.close()

def __cut(self):

self.__thisTextArea.event_generate("<<Cut>>")

def __copy(self):

self.__thisTextArea.event_generate("<<Copy>>")

def __paste(self):

self.__thisTextArea.event_generate("<<Paste>>")

def run(self):

self.__root.mainloop()

notepad = Notepad(width=600,height=400)

notepad.run()


21 Game

def nearestMultipleTo4(num):

if num >= 4:

near = num + (4 - (num % 4))

else:

near = 4

return near

def lose1():

print ("\n\nYOU LOSE !")

print("Better luck next time !")

exit(0)

# checks the numbers are consecutive

def check(xyz):

i = 1

while i<len(xyz):

if (xyz[i]-xyz[i-1])!= 1:

return False

i = i + 1

return True

def start1():

xyz = []

last = 0

while True:

print ("Enter 'F' to take the first chance.")

print("Enter 'S' to take the second chance.")

chance = input('> ')

#First Player

if chance == "F":

while True:

if last == 20:

lose1()

else:

print ("\nYour Turn.")

print ("\nHow many numbers do you wish to enter?")

inp = int(input('> '))

if inp > 0 and inp <= 3:

comp = 4 - inp

else:

print ("Wrong input. You are disqualified from the game.")

lose1()

i, j = 1, 1

print ("Now enter the values")

while i <= inp:

a = input('> ')

a = int(a)

xyz.append(a)

i = i + 1

# store the last element of xyz.

last = xyz[-1]

# check numbers are consecutive

if check(xyz) == True:

if last == 21:

lose1()

else:

#"Computer's turn."

while j <= comp:

xyz.append(last + j)

j = j + 1

print ("Order of inputs after computer's turn is: ")

print (xyz)

last = xyz[-1]

else:

print ("\nYou did not input consecutive integers.")

lose1()

# player takes the second chance

elif chance == "S":

comp = 1

last = 0

while last < 20:

#"Computer's turn"

j = 1

while j <= comp:

xyz.append(last + j)

j = j + 1

print ("Order of inputs after computer's turn is:")

print (xyz)

if xyz[-1] == 20:

lose1()

else:

print ("\nYour turn.")

print ("\nHow many numbers do you wish to enter?")

inp = input('> ')

inp = int(inp)

i = 1

print ("Enter your values")

while i <= inp:

xyz.append(int(input('> ')))

i = i + 1

last = xyz[-1]

if check(xyz) == True:

# print (xyz)

near = nearestMultipleTo4(last)

comp = near - last

if comp == 4:

comp = 3

else:

comp = comp

else:

# if inputs are not consecutive

# automatically disqualified

print ("\nYou did not input consecutive integers.")

# print ("You are disqualified from the game.")

lose1()

print ("\n\nCONGRATULATIONS !!!")

print ("YOU WON !")

exit(0)

else:

print ("wrong choice")

game = True

while game == True:

print ("Player 2 is Computer.")

print("Do you want to play the 21 number game? (Yes / No)")

ans = input('> ')

if ans =='Yes':

start1()

else:

print ("Do you want quit the game?(yes / no)")

nex = input('> ')

if nex == "yes":

print ("You are quitting the game...")

exit(0)

elif nex == "no":

print ("Continuing...")

else:

print ("Wrong choice")