diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py index 8b6d120cbf7..2316f5442ef 100644 --- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py +++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -20,7 +20,6 @@ student_record = os.getenv("STUDENTS_RECORD_FILE") import pickle -import logging # Define logger with info # import polar diff --git a/1 File handle/File handle binary/search record in binary file.py b/1 File handle/File handle binary/search record in binary file.py index a6529e15240..3e7729cf377 100644 --- a/1 File handle/File handle binary/search record in binary file.py +++ b/1 File handle/File handle binary/search record in binary file.py @@ -1,7 +1,6 @@ # binary file to search a given record import pickle -from dotenv import load_dotenv def search(): diff --git a/1 File handle/File handle text/input,output and error streams.py b/1 File handle/File handle text/input,output and error streams.py index 65c7b4462bc..5f712e6fbe7 100644 --- a/1 File handle/File handle text/input,output and error streams.py +++ b/1 File handle/File handle text/input,output and error streams.py @@ -9,7 +9,11 @@ ) as F: while True: ch = F.readlines() - for i in ch: # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words + for ( + i + ) in ( + ch + ): # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words print(i, end="") else: sys.stderr.write("End of file reached") diff --git a/Armstrong_number b/Armstrong_number index 7dd1b267ea0..3e73a7528bc 100644 --- a/Armstrong_number +++ b/Armstrong_number @@ -6,8 +6,9 @@ def is_armstrong_number(number): temp = 0 while num != 0: rem = num % 10 - num //= 10 - temp += rem ** length + num //= 10 + temp += rem**length return temp == number - + + is_armstrong_number(5) diff --git a/Automated Scheduled Call Reminders/caller.py b/Automated Scheduled Call Reminders/caller.py index f069da7df88..81471699385 100644 --- a/Automated Scheduled Call Reminders/caller.py +++ b/Automated Scheduled Call Reminders/caller.py @@ -40,7 +40,7 @@ def search(): for doc in list_of_docs: if doc["from"][0:5] == five_minutes_prior: phone_number = doc["phone"] - call = client.calls.create( + client.calls.create( to=phone_number, from_="add your twilio number", url="http://demo.twilio.com/docs/voice.xml", diff --git a/Automated Scheduled Call Reminders/requirements.txt b/Automated Scheduled Call Reminders/requirements.txt index f5635170c24..61824b3fac1 100644 --- a/Automated Scheduled Call Reminders/requirements.txt +++ b/Automated Scheduled Call Reminders/requirements.txt @@ -11,4 +11,4 @@ timedelta credentials firestore initialize_app -Twilio \ No newline at end of file +Twilio diff --git a/Binary_to_Decimal.py b/Binary_to_Decimal.py index ed477d502a6..43c39f63aa9 100644 --- a/Binary_to_Decimal.py +++ b/Binary_to_Decimal.py @@ -10,7 +10,7 @@ def binaryToDecimal(binary): >>> binaryToDecimal(101011) 43 """ - decimal, i, n = 0, 0, 0 + decimal, i, _n = 0, 0, 0 while binary != 0: dec = binary % 10 decimal = decimal + dec * pow(2, i) diff --git a/BoardGame-CLI/snakeLadder.py b/BoardGame-CLI/snakeLadder.py index fd06dd64527..84878ce8bda 100644 --- a/BoardGame-CLI/snakeLadder.py +++ b/BoardGame-CLI/snakeLadder.py @@ -59,7 +59,7 @@ def play(): print(f"you got {temp1}") print("") - if isReady[i] == False and temp1 == 6: + if not isReady[i] and temp1 == 6: isReady[i] = True if isReady[i]: @@ -90,7 +90,6 @@ def play(): elif n == 2: players = {} # stores player ans their locations isReady = {} - current_loc = 1 # reset starting location to 1 player_input() elif n == 3: diff --git a/CRC/crc.py b/CRC/crc.py index d3d302244b7..44e9f7bb0cf 100644 --- a/CRC/crc.py +++ b/CRC/crc.py @@ -1,6 +1,5 @@ def crc_check(data, div): l = len(div) - ct = 0 data = [int(i) for i in data] div = [int(i) for i in div] zero = [0 for i in range(l)] diff --git a/Checker_game_by_dz/first.py b/Checker_game_by_dz/first.py index 0b6825590f8..0ba81d67762 100644 --- a/Checker_game_by_dz/first.py +++ b/Checker_game_by_dz/first.py @@ -41,7 +41,7 @@ def get_row_col_mouse(pos): while run: clock.tick(fps) - if board.winner() != None: + if board.winner() is not None: print(board.winner()) # check if any events is running or not diff --git a/CliYoutubeDownloader/requirements.txt b/CliYoutubeDownloader/requirements.txt index 30257302458..cd5e770101f 100644 --- a/CliYoutubeDownloader/requirements.txt +++ b/CliYoutubeDownloader/requirements.txt @@ -1 +1 @@ -pytube \ No newline at end of file +pytube diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py index f6fa4d56507..373448813e9 100644 --- a/Colors/pixel_sort.py +++ b/Colors/pixel_sort.py @@ -135,19 +135,19 @@ def main(): ) # setting the threshold value for every row in the frame # For the specific row , if all the values are non-zero then it is sorted with color - if np.all(np.asarray(color)) == True: + if np.all(np.asarray(color)): color.sort(key=lambda bgr: step(bgr, 8)) # step sorting band, img = generateColors(color, img, row) measure(len(color), row, col, height, width) # For the specific row , if any of the values are zero it gets sorted with color_n - if np.all(np.asarray(color)) == False: + if not np.all(np.asarray(color)): for ind, i in enumerate(color): # Accessing every list within color # Added to color_n if any of the element in the list is non-zero # and their sum is less than threshold value - if np.any(np.asarray(i)) == True and sum(i) < thresh: + if np.any(np.asarray(i)) and sum(i) < thresh: color_n.append(i) color_n.sort(key=lambda bgr: step(bgr, 8)) # step sorting diff --git a/Day_of_week.py b/Day_of_week.py index c9c36bfada2..f0f9fd6f3b5 100644 --- a/Day_of_week.py +++ b/Day_of_week.py @@ -12,9 +12,9 @@ def process_date(user_input): def find_day(date): - born = ( - datetime.datetime.strptime(date, "%d %m %Y").weekday() - ) # this statement returns an integer corresponding to the day of the week + born = datetime.datetime.strptime( + date, "%d %m %Y" + ).weekday() # this statement returns an integer corresponding to the day of the week return calendar.day_name[ born ] # this statement returns the corresponding day name to the integer generated in the previous statement diff --git a/Downloaded Files Organizer/obs.py b/Downloaded Files Organizer/obs.py index 1489f257041..1c6d1b8609d 100644 --- a/Downloaded Files Organizer/obs.py +++ b/Downloaded Files Organizer/obs.py @@ -9,7 +9,7 @@ def watcher(path): class Handler(FileSystemEventHandler): def on_created(self, event): if event.event_type == "created": - file_name = os.path.basename(event.src_path) + os.path.basename(event.src_path) ext = os.path.splitext(event.src_path)[1] time.sleep(2) add_to_dir(ext[1:], event.src_path, path) diff --git a/Emoji Dictionary/QT_GUI.py b/Emoji Dictionary/QT_GUI.py index ef3f6f0cf40..71af4da2413 100644 --- a/Emoji Dictionary/QT_GUI.py +++ b/Emoji Dictionary/QT_GUI.py @@ -131,7 +131,8 @@ def clear_text(): button = QPushButton(emoji) button.setFixedSize(40, 40) button.setFont(QFont("Arial", 20)) - button.setStyleSheet(""" + button.setStyleSheet( + """ QPushButton { background-color: #ffffff; border: 1px solid #e0e0e0; @@ -140,7 +141,8 @@ def clear_text(): QPushButton:hover { background-color: #f0f0f0; } - """) + """ + ) button.clicked.connect(lambda checked, e=emoji: add_input_emoji(e)) self.emoji_layout.addWidget(button, row_idx, col_idx) self.emoji_buttons.append(button) diff --git a/EncryptionTool.py b/EncryptionTool.py index f6600752fa6..34e365189ae 100644 --- a/EncryptionTool.py +++ b/EncryptionTool.py @@ -48,11 +48,10 @@ def decrypt(enc_text): def readAndDecrypt(filename): file = open(filename, "r") data = file.read() - datalistint = [] actualdata = [] datalist = data.split(" ") datalist.remove("") - datalistint = [float(data) for data in datalist] + [float(data) for data in datalist] for data in datalist: current1 = int(decryptChar(data)) current1 = chr(current1) @@ -66,7 +65,6 @@ def readAndEncrypt(filename): data = file.read() datalist = list(data) encrypted_list = list() - encrypted_list_str = list() for data in datalist: current = ord(data) current = encryptChar(current) diff --git a/Extract-Table-from-pdf-txt-docx/main.py b/Extract-Table-from-pdf-txt-docx/main.py index d74649cd054..07e71ad90a2 100644 --- a/Extract-Table-from-pdf-txt-docx/main.py +++ b/Extract-Table-from-pdf-txt-docx/main.py @@ -6,16 +6,16 @@ # %% -if os.path.isdir("Parent") == True: +if os.path.isdir("Parent"): os.chdir("Parent") # FOR CHILD1 DIRECTORY -if os.path.isdir("Child1") == True: +if os.path.isdir("Child1"): os.chdir("Child1") # PDF FILE READING -if os.path.isfile("Pdf1_Child1.pdf") == True: +if os.path.isfile("Pdf1_Child1.pdf"): df_pdf_child1 = tabula.read_pdf("Pdf1_Child1.pdf", pages="all") # DOCUMENT READING -if os.path.isfile("Document_Child1.docx") == True: +if os.path.isfile("Document_Child1.docx"): document = Document("Document_Child1.docx") table = document.tables[0] data = [] @@ -30,7 +30,7 @@ data.append(row_data) df_document_child1 = pd.DataFrame(data) # TEXT READING -if os.path.isfile("Text_Child1.txt") == True: +if os.path.isfile("Text_Child1.txt"): df_text_child1 = pd.read_csv("Text_Child1.txt") # %% @@ -39,16 +39,16 @@ # %% os.chdir("../") -if os.path.isdir("Parent") == True: +if os.path.isdir("Parent"): os.chdir("Parent") # FOR CHILD2 DIRECTORY -if os.path.isdir("Child2") == True: +if os.path.isdir("Child2"): os.chdir("Child2") # PDF FILE READING -if os.path.isfile("Pdf1_Child2.pdf") == True: +if os.path.isfile("Pdf1_Child2.pdf"): df_pdf_child2 = tabula.read_pdf("Pdf1_Child2.pdf", pages="all") # DOCUMENT READING -if os.path.isfile("Document_Child2.docx") == True: +if os.path.isfile("Document_Child2.docx"): document = Document("Document_Child2.docx") table = document.tables[0] data = [] @@ -63,7 +63,7 @@ data.append(row_data) df_document_child2 = pd.DataFrame(data) # TEXT READING -if os.path.isfile("Text_Child2.txt") == True: +if os.path.isfile("Text_Child2.txt"): df_text_child2 = pd.read_csv("Text_Child2.txt") # %% @@ -71,16 +71,16 @@ # %% os.chdir("../") -if os.path.isdir("Parent") == True: +if os.path.isdir("Parent"): os.chdir("Parent") # FOR CHILD3 DIRECTORY -if os.path.isdir("Child3") == True: +if os.path.isdir("Child3"): os.chdir("Child3") # PDF FILE READING -if os.path.isfile("Pdf1_Child3.pdf") == True: +if os.path.isfile("Pdf1_Child3.pdf"): df_pdf_child3 = tabula.read_pdf("Pdf1_Child3.pdf", pages="all") # DOCUMENT READING -if os.path.isfile("Document_Child3.docx") == True: +if os.path.isfile("Document_Child3.docx"): document = Document("Document_Child3.docx") table = document.tables[0] data = [] @@ -95,7 +95,7 @@ data.append(row_data) df_document_child3 = pd.DataFrame(data) # TEXT READING -if os.path.isfile("Text_Child3.txt") == True: +if os.path.isfile("Text_Child3.txt"): df_text_child3 = pd.read_csv("Text_Child3.txt") # %% diff --git a/FibonacciNumbersWithGenerators.py b/FibonacciNumbersWithGenerators.py index 15771630222..49d35aae1e5 100644 --- a/FibonacciNumbersWithGenerators.py +++ b/FibonacciNumbersWithGenerators.py @@ -8,7 +8,7 @@ def fibonacci_generator(n=None): """ f0, f1 = 0, 1 yield f1 - while n == None or n > 1: + while n is None or n > 1: fn = f0 + f1 yield fn f0, f1 = f1, fn diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py index d42f4a3ac86..a50bc3b49e6 100644 --- a/Google_Image_Downloader/image_grapper.py +++ b/Google_Image_Downloader/image_grapper.py @@ -58,7 +58,7 @@ def search_for_image(): results = sew.findAll("div", {"class": "rg_meta"}) for re in results: - (link, Type) = (json.loads(re.text)["ou"], json.loads(re.text)["ity"]) + (link, _Type) = (json.loads(re.text)["ou"], json.loads(re.text)["ity"]) images.append(link) counter = 0 for re in images: diff --git a/Grocery calculator.py b/Grocery calculator.py index 42adbb7cd74..7505d958c06 100644 --- a/Grocery calculator.py +++ b/Grocery calculator.py @@ -11,7 +11,7 @@ # Methods = addToList, Total, Subtotal, returnList class GroceryList(dict): def __init__(self): - self = {} + pass def addToList(self, item, price): self.update({item: price}) diff --git a/Industrial_developed_hangman/src/hangman/main.py b/Industrial_developed_hangman/src/hangman/main.py index 3839d9222f1..7ef112c94f5 100644 --- a/Industrial_developed_hangman/src/hangman/main.py +++ b/Industrial_developed_hangman/src/hangman/main.py @@ -126,7 +126,9 @@ def user_lose(self) -> None: def user_win(self) -> None: """Print text for end of game and exits.""" - print_wrong(f"{self._word_string_to_show} YOU WON", self._print_function) # noqa:WPS305 + print_wrong( + f"{self._word_string_to_show} YOU WON", self._print_function + ) # noqa:WPS305 def game_process(self, user_character: str) -> bool: # noqa: DAR201 diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py index 597cd35cef3..541bac2c995 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -1,5 +1,6 @@ # Python program to convert infix expression to postfix + # Class to convert the expression class Conversion: # Constructor to initialize the class variables diff --git a/JARVIS/JARVIS_2.0.py b/JARVIS/JARVIS_2.0.py index 676c6b833ce..c57b3044834 100644 --- a/JARVIS/JARVIS_2.0.py +++ b/JARVIS/JARVIS_2.0.py @@ -258,7 +258,7 @@ def get_app(Q): webbrowser.open("https://github.com/") elif Q == "search for": que = Q.lstrip("search for") - answer = ask_gpt3(que) + ask_gpt3(que) elif ( Q == "email to other" @@ -269,7 +269,7 @@ def get_app(Q): with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 - audio = r.listen(source) + r.listen(source) to = "abc@gmail.com" content = input("Enter content") sendEmail(to, content) @@ -307,11 +307,11 @@ def get_app(Q): elif Q == "take a break": exit() else: - answer = ask_gpt3(Q) + ask_gpt3(Q) # master - apps = { + { "time": datetime.datetime.now(), "notepad": "Notepad.exe", "calculator": "calc.exe", diff --git a/JARVIS/requirements.txt b/JARVIS/requirements.txt index ca6bbccddbd..8c113ef6596 100644 --- a/JARVIS/requirements.txt +++ b/JARVIS/requirements.txt @@ -10,4 +10,4 @@ key playsound pyttsx3 SpeechRecognition -openai \ No newline at end of file +openai diff --git a/Key_Binding/requirement.txt b/Key_Binding/requirement.txt index 51d89fc61fc..9848dc29115 100644 --- a/Key_Binding/requirement.txt +++ b/Key_Binding/requirement.txt @@ -1 +1 @@ -quo>=2022.4 +quo >= 2022.4 diff --git a/Letter_Counter.py b/Letter_Counter.py index b900c72b4dc..77b7530e926 100644 --- a/Letter_Counter.py +++ b/Letter_Counter.py @@ -16,7 +16,7 @@ def printt(): # Get the count and display results. letter_count = message.count(letter) a = "your message has " + str(letter_count) + " " + letter + "'s in it." - labl = tk.Label(root, text=a, font=("arial", 15), fg="black").place(x=10, y=220) + tk.Label(root, text=a, font=("arial", 15), fg="black").place(x=10, y=220) lbl = tk.Label(root, text="Enter the Message--", font=("Ubuntu", 15), fg="black").place( diff --git a/LinkedLists all Types/doubly_linked_list.py b/LinkedLists all Types/doubly_linked_list.py index ed451dc58cd..715005f6003 100644 --- a/LinkedLists all Types/doubly_linked_list.py +++ b/LinkedLists all Types/doubly_linked_list.py @@ -23,7 +23,7 @@ def __init__(self): def insert_front(self, data): node = Node(data, self.head) - if self.head == None: + if self.head is None: self.tail = node node.prev = self.head self.head = node @@ -31,7 +31,7 @@ def insert_front(self, data): def insert_back(self, data): node = Node(data, None, self.tail) - if self.head == None: + if self.head is None: self.tail = self.head = node self.length += 1 else: @@ -72,7 +72,7 @@ def print(self): temp = self.head print("NULL <-", end=" ") while temp: - if temp.next == None: + if temp.next is None: print(f"{temp.data} ->", end=" ") break print(f"{temp.data} <=>", end=" ") @@ -158,7 +158,7 @@ def remove_by_value(self, idx_data): temp.next.prev = temp.prev self.length -= 1 return - if temp != None: + if temp is not None: temp = temp.next print("The Element is not the List!") @@ -195,7 +195,7 @@ def reverse(self): return prev = c_next = None curr = self.head - while curr != None: + while curr is not None: c_next = curr.next curr.next = prev prev = curr @@ -209,7 +209,7 @@ def mid_element(self): return slow = self.head.next fast = self.head.next.next - while fast != None and fast.next != None: + while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow.data diff --git a/LinkedLists all Types/singly_linked_list.py b/LinkedLists all Types/singly_linked_list.py index f1242b29cf8..eeeec94b2ce 100644 --- a/LinkedLists all Types/singly_linked_list.py +++ b/LinkedLists all Types/singly_linked_list.py @@ -22,14 +22,14 @@ def __init__(self): def insert_front(self, data): node = Node(data, self.head) - if self.head == None: + if self.head is None: self.tail = node self.head = node self.length += 1 def insert_back(self, data): node = Node(data) - if self.head == None: + if self.head is None: self.tail = self.head = node self.length += 1 else: @@ -142,7 +142,7 @@ def remove_by_value(self, idx_data): self.length -= 1 temp.next = None return - while temp.next != None: + while temp.next is not None: if temp.next.data == idx_data: temp.next = temp.next.next self.length -= 1 @@ -184,7 +184,7 @@ def reverse(self): return prev = c_next = None curr = self.head - while curr != None: + while curr is not None: c_next = curr.next curr.next = prev prev = curr @@ -198,7 +198,7 @@ def mid_element(self): return slow = self.head.next fast = self.head.next.next - while fast != None and fast.next != None: + while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow.data diff --git a/Merge_linked_list.py b/Merge_linked_list.py index b5b38a7a132..667148ee0e3 100644 --- a/Merge_linked_list.py +++ b/Merge_linked_list.py @@ -1,6 +1,7 @@ # Python3 program merge two sorted linked # in third linked list using recursive. + # Node class class Node: def __init__(self, data): diff --git a/MySQL_Databses.py b/MySQL_Databses.py index 226a20e742c..4e1a795d72d 100644 --- a/MySQL_Databses.py +++ b/MySQL_Databses.py @@ -1,4 +1,5 @@ import mysql.connector + # MySQl databses details host = input("Enter MySQL host: ") username = input("Enter MySQL username: ") diff --git a/News_App/patterns.py b/News_App/patterns.py index 7d1074c65d3..c576512469f 100644 --- a/News_App/patterns.py +++ b/News_App/patterns.py @@ -98,7 +98,6 @@ "KOTAK MAHINDRA BANK ": "KOTAKBANK.NS", "LARSEN AND TOUBRO ": "LT.NS", "MAHINDRA AND MAHINDRA ": "M&M.NS", - "MARUTI SUZUKI INDIA ": "MARUTI.NS", "NTPC ": "NTPC.NS", "NESTLE INDIA ": "NESTLEIND.NS", "OIL AND NATURAL GAS CORPORATION ": "ONGC.NS", diff --git a/PONG_GAME.py b/PONG_GAME.py index 59b6e566c3d..8ddec6661de 100644 --- a/PONG_GAME.py +++ b/PONG_GAME.py @@ -45,14 +45,7 @@ def new_game(): def draw(canvas): - global \ - paddle1_pos, \ - paddle2_pos, \ - ball_pos, \ - ball_vel, \ - paddle1_vel, \ - paddle2_vel, \ - BALL_RADIUS + global paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel, BALL_RADIUS global score1, score2 canvas.draw_line([WIDTH / 2, 0], [WIDTH / 2, HEIGHT], 1, "White") diff --git a/PORT SCANNER.PY b/PORT SCANNER.PY index 594ea3eb16f..56093829e32 100644 --- a/PORT SCANNER.PY +++ b/PORT SCANNER.PY @@ -75,7 +75,9 @@ from time import time import platform # Clear the screen -subprocess.call('clear' if platform.platform() in ("Linux", "Darwin") else "cls", shell=True) +subprocess.call( + "clear" if platform.platform() in ("Linux", "Darwin") else "cls", shell=True +) # Ask for input remoteServer = input("Enter a remote host to scan: ") @@ -106,7 +108,7 @@ except KeyboardInterrupt: sys.exit(2) except socket.gaierror: - print('Hostname could not be resolved. Exiting') + print("Hostname could not be resolved. Exiting") sys.exit(1) except socket.error: @@ -120,4 +122,4 @@ t2 = time() total = t2 - t1 # Printing the information to screen -print('Scanning Completed in about {total} seconds', total) +print("Scanning Completed in about {total} seconds", total) diff --git a/Password Manager Using Tkinter/PGV.py b/Password Manager Using Tkinter/PGV.py index 045625ea650..9e107c802d8 100644 --- a/Password Manager Using Tkinter/PGV.py +++ b/Password Manager Using Tkinter/PGV.py @@ -1,11 +1,8 @@ import json new_data = { - website_input.get():{ - "email": email_input.get(), - "password": passw_input.get() - } - } + website_input.get(): {"email": email_input.get(), "password": passw_input.get()} +} try: with open("data.json", "r") as data_file: @@ -15,4 +12,4 @@ pass else: with open("data.json", "w") as data_file: - json.dump(new_data, data_file, indent = 4) \ No newline at end of file + json.dump(new_data, data_file, indent=4) diff --git a/Password Manager Using Tkinter/data.json b/Password Manager Using Tkinter/data.json index 399ea997575..64d473ed71b 100644 --- a/Password Manager Using Tkinter/data.json +++ b/Password Manager Using Tkinter/data.json @@ -1,14 +1,14 @@ { "Amazon": { "email": "prashant123Amazon@gmail.com", - "password": "1mD%#Z555rF$&2aRpI" + "password": "1mD%#Z555rF$&2aRpI", }, "Facebook": { "email": "prashant123Facebook@gmail.com", - "password": "qQ6#H7o&)i8S!3sO)c4" + "password": "qQ6#H7o&)i8S!3sO)c4", }, "Flipkart": { "email": "prashant123Flipkart@gmail.com", - "password": "1!+7NqmUZbN18K(3A+" - } -} \ No newline at end of file + "password": "1!+7NqmUZbN18K(3A+", + }, +} diff --git a/Password Manager Using Tkinter/main.py b/Password Manager Using Tkinter/main.py index 15d6fdc1d13..c66072bea99 100644 --- a/Password Manager Using Tkinter/main.py +++ b/Password Manager Using Tkinter/main.py @@ -12,12 +12,66 @@ # in a real application, this should be changed and stored securely (e.g., hashed and salted). MASTER_PASSWORD = "password123" + # ---------------------------- PASSWORD GENERATOR ------------------------------- # def generate_password(): """generates a random strong password and copies it to clipboard.""" - letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] - numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] - symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] + letters = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + ] + numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + symbols = ["!", "#", "$", "%", "&", "(", ")", "*", "+"] password_letters = [choice(letters) for _ in range(randint(8, 10))] password_symbols = [choice(symbols) for _ in range(randint(2, 4))] @@ -30,7 +84,10 @@ def generate_password(): password_entry.delete(0, tk.END) password_entry.insert(0, password) pyperclip.copy(password) - messagebox.showinfo(title="Password Generated", message="Password copied to clipboard!") + messagebox.showinfo( + title="Password Generated", message="Password copied to clipboard!" + ) + # ---------------------------- SAVE PASSWORD ------------------------------- # def save(): @@ -46,18 +103,23 @@ def save(): } if not website or not password: - messagebox.showerror(title="Oops", message="Please don't leave any fields empty!") + messagebox.showerror( + title="Oops", message="Please don't leave any fields empty!" + ) return - is_ok = messagebox.askokcancel(title=website, message=f"These are the details entered: \nEmail: {email} " - f"\nPassword: {password} \nIs it ok to save?") + is_ok = messagebox.askokcancel( + title=website, + message=f"These are the details entered: \nEmail: {email} " + f"\nPassword: {password} \nIs it ok to save?", + ) if is_ok: try: with open("data.json", "r") as data_file: data = json.load(data_file) except (FileNotFoundError, json.JSONDecodeError): data = {} - + data.update(new_data) with open("data.json", "w") as data_file: @@ -66,6 +128,7 @@ def save(): website_entry.delete(0, tk.END) password_entry.delete(0, tk.END) + # ---------------------------- FIND PASSWORD ------------------------------- # def find_password(): """finds and displays password for a given website.""" @@ -76,91 +139,123 @@ def find_password(): except (FileNotFoundError, json.JSONDecodeError): messagebox.showerror(title="Error", message="No Data File Found.") return - + if website in data: email = data[website]["email"] password = data[website]["password"] - messagebox.showinfo(title=website, message=f"Email: {email}\nPassword: {password}") + messagebox.showinfo( + title=website, message=f"Email: {email}\nPassword: {password}" + ) pyperclip.copy(password) - messagebox.showinfo(title="Copied", message="Password for {} copied to clipboard.".format(website)) + messagebox.showinfo( + title="Copied", + message="Password for {} copied to clipboard.".format(website), + ) else: messagebox.showerror(title="Error", message=f"No details for {website} exists.") + # ---------------------------- VIEW ALL PASSWORDS ------------------------------- # def view_all_passwords(): """prompts for master password and displays all saved passwords if correct.""" - password = simpledialog.askstring("Master Password", "Please enter the master password:", show='*') - + password = simpledialog.askstring( + "Master Password", "Please enter the master password:", show="*" + ) + if password == MASTER_PASSWORD: show_passwords_window() - elif password is not None: # avoids error message if user clicks cancel - messagebox.showerror("Incorrect Password", "The master password you entered is incorrect.") + elif password is not None: # avoids error message if user clicks cancel + messagebox.showerror( + "Incorrect Password", "The master password you entered is incorrect." + ) + def show_passwords_window(): """creates a new window to display all passwords in a table.""" all_passwords_window = tk.Toplevel(window) all_passwords_window.title("All Saved Passwords") all_passwords_window.config(padx=20, pady=20) - + # a frame for the treeview and scrollbar tree_frame = ttk.Frame(all_passwords_window) - tree_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') - + tree_frame.grid(row=0, column=0, columnspan=2, sticky="nsew") + # a Treeview (table) - cols = ('Website', 'Email', 'Password') - tree = ttk.Treeview(tree_frame, columns=cols, show='headings') - + cols = ("Website", "Email", "Password") + tree = ttk.Treeview(tree_frame, columns=cols, show="headings") + # column headings and widths - tree.heading('Website', text='Website') - tree.column('Website', width=150) - tree.heading('Email', text='Email/Username') - tree.column('Email', width=200) - tree.heading('Password', text='Password') - tree.column('Password', width=200) - - tree.grid(row=0, column=0, sticky='nsew') + tree.heading("Website", text="Website") + tree.column("Website", width=150) + tree.heading("Email", text="Email/Username") + tree.column("Email", width=200) + tree.heading("Password", text="Password") + tree.column("Password", width=200) + + tree.grid(row=0, column=0, sticky="nsew") # a scrollbar scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree.yview) tree.configure(yscroll=scrollbar.set) - scrollbar.grid(row=0, column=1, sticky='ns') + scrollbar.grid(row=0, column=1, sticky="ns") # load data from JSON file try: with open("data.json", "r") as data_file: data = json.load(data_file) - + # insert data into the treeview for website, details in data.items(): - tree.insert("", "end", values=(website, details['email'], details['password'])) - + tree.insert( + "", "end", values=(website, details["email"], details["password"]) + ) + except (FileNotFoundError, json.JSONDecodeError): # if file not found or empty, it will just show an empty table pass - + def copy_selected_info(column_index, info_type): """copies the email or password of the selected row.""" selected_item = tree.focus() if not selected_item: - messagebox.showwarning("No Selection", "Please select a row from the table first.", parent=all_passwords_window) + messagebox.showwarning( + "No Selection", + "Please select a row from the table first.", + parent=all_passwords_window, + ) return - - item_values = tree.item(selected_item, 'values') + + item_values = tree.item(selected_item, "values") info_to_copy = item_values[column_index] pyperclip.copy(info_to_copy) - messagebox.showinfo("Copied!", f"The {info_type.lower()} for '{item_values[0]}' has been copied to your clipboard.", parent=all_passwords_window) + messagebox.showinfo( + "Copied!", + f"The {info_type.lower()} for '{item_values[0]}' has been copied to your clipboard.", + parent=all_passwords_window, + ) # a frame for the buttons button_frame = ttk.Frame(all_passwords_window) - button_frame.grid(row=1, column=0, columnspan=2, pady=(10,0)) + button_frame.grid(row=1, column=0, columnspan=2, pady=(10, 0)) - copy_email_button = ttk.Button(button_frame, text="Copy Email", style="success.TButton", command=lambda: copy_selected_info(1, "Email")) + copy_email_button = ttk.Button( + button_frame, + text="Copy Email", + style="success.TButton", + command=lambda: copy_selected_info(1, "Email"), + ) copy_email_button.pack(side=tk.LEFT, padx=5) - copy_password_button = ttk.Button(button_frame, text="Copy Password", style="success.TButton", command=lambda: copy_selected_info(2, "Password")) + copy_password_button = ttk.Button( + button_frame, + text="Copy Password", + style="success.TButton", + command=lambda: copy_selected_info(2, "Password"), + ) copy_password_button.pack(side=tk.LEFT, padx=5) - all_passwords_window.grab_set() # makes window modal + all_passwords_window.grab_set() # makes window modal + # ---------------------------- UI SETUP ------------------------------- # window = ttk.Window(themename="superhero") @@ -192,16 +287,21 @@ def copy_selected_info(column_index, info_type): password_entry.grid(row=3, column=1, pady=5, sticky="EW") # buttons -search_button = ttk.Button(text="Search", width=14, command=find_password, style="info.TButton") -search_button.grid(row=1, column=2, sticky="EW", padx=(5,0)) -generate_password_button = ttk.Button(text="Generate Password", command=generate_password, style="success.TButton") -generate_password_button.grid(row=3, column=2, sticky="EW", padx=(5,0)) +search_button = ttk.Button( + text="Search", width=14, command=find_password, style="info.TButton" +) +search_button.grid(row=1, column=2, sticky="EW", padx=(5, 0)) +generate_password_button = ttk.Button( + text="Generate Password", command=generate_password, style="success.TButton" +) +generate_password_button.grid(row=3, column=2, sticky="EW", padx=(5, 0)) add_button = ttk.Button(text="Add", width=43, command=save, style="primary.TButton") -add_button.grid(row=4, column=1, columnspan=2, pady=(10,0), sticky="EW") +add_button.grid(row=4, column=1, columnspan=2, pady=(10, 0), sticky="EW") -view_all_button = ttk.Button(text="View All Passwords", command=view_all_passwords, style="secondary.TButton") -view_all_button.grid(row=5, column=1, columnspan=2, pady=(10,0), sticky="EW") +view_all_button = ttk.Button( + text="View All Passwords", command=view_all_passwords, style="secondary.TButton" +) +view_all_button.grid(row=5, column=1, columnspan=2, pady=(10, 0), sticky="EW") window.mainloop() - diff --git a/Password Manager Using Tkinter/requirements.txt b/Password Manager Using Tkinter/requirements.txt index 60ffacab8a4..b49506e51c07 100644 --- a/Password Manager Using Tkinter/requirements.txt +++ b/Password Manager Using Tkinter/requirements.txt @@ -1 +1 @@ -ttkbootstrap \ No newline at end of file +ttkbootstrap diff --git a/Python Programs/Python Program to Reverse a linked list.py b/Python Programs/Python Program to Reverse a linked list.py index e636a0df632..53ae08df10e 100644 --- a/Python Programs/Python Program to Reverse a linked list.py +++ b/Python Programs/Python Program to Reverse a linked list.py @@ -2,6 +2,7 @@ # Time Complexity : O(n) # Space Complexity : O(1) + # Node class class Node: # Constructor to initialize the node object diff --git a/Python_chatting_application/client.py b/Python_chatting_application/client.py index 447e7b6c448..1bddaa54ceb 100644 --- a/Python_chatting_application/client.py +++ b/Python_chatting_application/client.py @@ -20,7 +20,6 @@ def recieve(): except Exception as error: print(f"An Erro occured {error}") s.close() - flag = 1 break @@ -32,7 +31,6 @@ def Write(): except Exception as error: print(f"An Error Occured while sending message !!!\n error : {error}") s.close() - flag = 1 break diff --git a/Python_swapping.py b/Python_swapping.py index 1822f2f1bc3..a740662acf0 100644 --- a/Python_swapping.py +++ b/Python_swapping.py @@ -1,6 +1,7 @@ # Python3 program to swap first # and last element of a list + # Swap function def swapList(newList): size = len(newList) diff --git a/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py index 51a48b692b9..4965d331cdb 100755 --- a/QR_code_generator/qrcode.py +++ b/QR_code_generator/qrcode.py @@ -1,4 +1,5 @@ import pyqrcode + # from pyqrcode import QRCode # no need to import same library again and again diff --git a/QuestionAnswerVirtualAssistant/backend.py b/QuestionAnswerVirtualAssistant/backend.py index 3746a93cb69..7a7c5f2a257 100644 --- a/QuestionAnswerVirtualAssistant/backend.py +++ b/QuestionAnswerVirtualAssistant/backend.py @@ -74,7 +74,7 @@ def index_question_answer(self, question, answer): reverse_idx[word].append(row_id) reverse_idx = json.dumps(reverse_idx) cur = self.conn.cursor() - result = cur.execute( + cur.execute( "UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,) ) return "index successful" diff --git a/QuestionAnswerVirtualAssistant/requirements.txt b/QuestionAnswerVirtualAssistant/requirements.txt index fb4d28890ad..ff3211e9a15 100644 --- a/QuestionAnswerVirtualAssistant/requirements.txt +++ b/QuestionAnswerVirtualAssistant/requirements.txt @@ -1,2 +1,2 @@ pandas -scikit-learn \ No newline at end of file +scikit - learn diff --git a/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py b/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py index df3e705cbc0..b34c85937b1 100644 --- a/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py +++ b/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py @@ -1,20 +1,17 @@ - -''' +""" This file is responsible for fetching quiz questions from the Open Trivia Database API. -''' +""" import requests -parameters = { - "amount": 10, - "type": "multiple", - "category": 18 -} +parameters = {"amount": 10, "type": "multiple", "category": 18} error_message = "" try: - response = requests.get(url="https://opentdb.com/api.php", params=parameters, timeout=10) + response = requests.get( + url="https://opentdb.com/api.php", params=parameters, timeout=10 + ) response.raise_for_status() # Raise an exception for HTTP errors question_data = response.json()["results"] print("Questions loaded successfully from the API.") diff --git a/Quizzler Using Tkinter and Trivia DB API/data_static.py b/Quizzler Using Tkinter and Trivia DB API/data_static.py index 081bc3982a2..5ea00107aca 100644 --- a/Quizzler Using Tkinter and Trivia DB API/data_static.py +++ b/Quizzler Using Tkinter and Trivia DB API/data_static.py @@ -5,8 +5,8 @@ "incorrect_answers": [ "Increase in hardware prices", "Decrease in computational power", - "Less complex problems for software engineers" - ] + "Less complex problems for software engineers", + ], }, { "question": "How have software engineers coped with the challenges of increasing computational capabilities?", @@ -14,8 +14,8 @@ "incorrect_answers": [ "By reducing programming efforts", "By simplifying programming languages", - "By avoiding large and complex problems" - ] + "By avoiding large and complex problems", + ], }, { "question": "Which of the following is a definition of software engineering according to IEEE?", @@ -23,8 +23,8 @@ "incorrect_answers": [ "The art of writing computer programs", "An engineering approach to developing software", - "A collection of unorganized programming techniques" - ] + "A collection of unorganized programming techniques", + ], }, { "question": "Why is software engineering similar to other engineering disciplines?", @@ -32,8 +32,8 @@ "incorrect_answers": [ "It makes use of subjective judgement and ill understood principles", "It often avoids conflicting goals", - "It relies solely on qualitative attributes" - ] + "It relies solely on qualitative attributes", + ], }, { "question": "Which statement supports the idea that software engineering is not just an art?", @@ -41,8 +41,8 @@ "incorrect_answers": [ "It makes subjective judgement based on qualitative attributes", "It avoids systematic and disciplined approaches", - "It does not require tradeoffs in problem solving" - ] + "It does not require tradeoffs in problem solving", + ], }, { "question": "How have software engineering principles evolved over the last sixty years?", @@ -50,17 +50,13 @@ "incorrect_answers": [ "From a science to an art form", "From a craft to an art form", - "From an engineering discipline to a craft" - ] + "From an engineering discipline to a craft", + ], }, { "question": "Which programming style is characterized by quickly developing a program without any specification, plan, or design?", "correct_answer": "Build and fix", - "incorrect_answers": [ - "Exploratory", - "Code and fix", - "Ad hoc" - ] + "incorrect_answers": ["Exploratory", "Code and fix", "Ad hoc"], }, { "question": "According to the text, what has been a symptom of the present software crisis?", @@ -68,8 +64,8 @@ "incorrect_answers": [ "Decrease in software development costs", "Software products becoming easier to alter and debug", - "Software products being delivered on time" - ] + "Software products being delivered on time", + ], }, { "question": "What is one of the main benefits of adopting software engineering techniques according to the text?", @@ -77,8 +73,8 @@ "incorrect_answers": [ "Increasing hardware costs", "Avoiding the use of scientific principles", - "Making software development more subjective" - ] + "Making software development more subjective", + ], }, { "question": "What is a key characteristic of toy software?", @@ -86,9 +82,9 @@ "incorrect_answers": [ "Developed by a team of professionals", "Large in size and highly complex", - "Thoroughly tested and maintained" - ] - } + "Thoroughly tested and maintained", + ], + }, # { # "question": "What differentiates professional software from toy software?", # "correct_answer": "Professional software is systematically designed, carefully implemented, and thoroughly tested", @@ -188,4 +184,4 @@ # "Data flow-oriented design" # ] # } -] \ No newline at end of file +] diff --git a/Quizzler Using Tkinter and Trivia DB API/main.py b/Quizzler Using Tkinter and Trivia DB API/main.py index 37a038c5d60..c6823ac1964 100644 --- a/Quizzler Using Tkinter and Trivia DB API/main.py +++ b/Quizzler Using Tkinter and Trivia DB API/main.py @@ -1,4 +1,3 @@ - """This file processes the fetched questions and prepares them for use in the quiz.""" from question_model import Question @@ -18,7 +17,7 @@ Question( question["question"], question["correct_answer"], - question["incorrect_answers"] + [question["correct_answer"]] + question["incorrect_answers"] + [question["correct_answer"]], ) for question in question_data ] diff --git a/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py b/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py index 53bcf178931..95212861a79 100644 --- a/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py +++ b/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py @@ -1,8 +1,8 @@ - """This file contains the logic that drives the quiz game, including managing the current question, checking answers, and tracking the score.""" import html + class QuizBrain: def __init__(self, q_list): self.question_number = 0 diff --git a/Quizzler Using Tkinter and Trivia DB API/ui.py b/Quizzler Using Tkinter and Trivia DB API/ui.py index 42102c20fac..28cd558ff55 100644 --- a/Quizzler Using Tkinter and Trivia DB API/ui.py +++ b/Quizzler Using Tkinter and Trivia DB API/ui.py @@ -1,4 +1,3 @@ - """This file manages the graphical user interface of the quiz, using Tkinter to display questions, answer options, and the score to the user.""" from tkinter import * @@ -22,20 +21,29 @@ FONT = ("Lucida sans", 20) -class QuizInterface: +class QuizInterface: def __init__(self, quiz_brain: QuizBrain): self.quiz = quiz_brain self.window = Tk() self.window.title("Quizzler") self.window.config(padx=20, pady=20, bg=BACKGROUND) - self.score_label = Label(text="Score: 0", fg="white", bg=BACKGROUND, font=("Lucida sans", 15, "bold")) + self.score_label = Label( + text="Score: 0", fg="white", bg=BACKGROUND, font=("Lucida sans", 15, "bold") + ) self.score_label.grid(row=0, column=1) self.canvas = Canvas(width=1000, height=550, bg=CANVAS) self.question_text = self.canvas.create_text( - 500, 100, width=800, text="Some question text", fill=TEXT, font=FONT, anchor="center", justify="center" + 500, + 100, + width=800, + text="Some question text", + fill=TEXT, + font=FONT, + anchor="center", + justify="center", ) self.canvas.grid(row=1, column=0, columnspan=2, pady=50) @@ -59,8 +67,16 @@ def create_radio_buttons(self): y_position = 230 for i in range(4): radio_button = Radiobutton( - self.canvas, text="", variable=self.opt_selected, value=i + 1, font=FONT, bg=CANVAS, anchor="w", - justify="left", fg=TEXT, wraplength=900 + self.canvas, + text="", + variable=self.opt_selected, + value=i + 1, + font=FONT, + bg=CANVAS, + anchor="w", + justify="left", + fg=TEXT, + wraplength=900, ) radio_buttons.append(radio_button) self.canvas.create_window(50, y_position, window=radio_button, anchor="w") diff --git a/Search_Engine/backend.py b/Search_Engine/backend.py index 2c4f730b914..35332a49f58 100644 --- a/Search_Engine/backend.py +++ b/Search_Engine/backend.py @@ -69,7 +69,7 @@ def index_document(self, document): reverse_idx[word].append(row_id) reverse_idx = json.dumps(reverse_idx) cur = self.conn.cursor() - result = cur.execute( + cur.execute( "UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,) ) return "index successful" diff --git a/Snake Game Using Turtle/colors.py b/Snake Game Using Turtle/colors.py index 05fac02e5a2..9b4d6ab1db2 100644 --- a/Snake Game Using Turtle/colors.py +++ b/Snake Game Using Turtle/colors.py @@ -2,27 +2,27 @@ This file contains the color palette for the game, now including colors for the new interactive buttons. """ + # A fresh and vibrant color theme # --> food.py FOOD_COLOR = "#C70039" # A bright, contrasting red # --> main.py -BG_COLOR = '#F0F8FF' # AliceBlue, a very light and clean background +BG_COLOR = "#F0F8FF" # AliceBlue, a very light and clean background # --> scoreboard.py -GAME_OVER_COLOR = '#D21312' # Strong red for game over message -SCORE_COLOR = '#27374D' # Dark blue for high-contrast text -MESSAGE_COLOR = '#27374D' # Consistent dark blue for other messages +GAME_OVER_COLOR = "#D21312" # Strong red for game over message +SCORE_COLOR = "#27374D" # Dark blue for high-contrast text +MESSAGE_COLOR = "#27374D" # Consistent dark blue for other messages # --> snake.py -FIRST_SEGMENT_COLOR = '#006400' # DarkGreen for the snake's head -BODY_COLOR = '#2E8B57' # SeaGreen for the snake's body +FIRST_SEGMENT_COLOR = "#006400" # DarkGreen for the snake's head +BODY_COLOR = "#2E8B57" # SeaGreen for the snake's body # --> wall.py -WALL_COLOR = '#27374D' # Dark blue for a solid, visible border +WALL_COLOR = "#27374D" # Dark blue for a solid, visible border # --> UI Controls (Buttons) BUTTON_BG_COLOR = "#526D82" BUTTON_TEXT_COLOR = "#F0F8FF" BUTTON_BORDER_COLOR = "#27374D" - diff --git a/Snake Game Using Turtle/food.py b/Snake Game Using Turtle/food.py index 59dcd5eb740..72a141aea94 100644 --- a/Snake Game Using Turtle/food.py +++ b/Snake Game Using Turtle/food.py @@ -7,8 +7,10 @@ import random import colors + class Food(Turtle): - """ This class generates food for the snake to eat. """ + """This class generates food for the snake to eat.""" + def __init__(self): super().__init__() self.shape("circle") @@ -24,4 +26,3 @@ def refresh(self, left_wall, right_wall, bottom_wall, top_wall): random_x = random.randint(int(left_wall) + margin, int(right_wall) - margin) random_y = random.randint(int(bottom_wall) + margin, int(top_wall) - margin) self.goto(random_x, random_y) - diff --git a/Snake Game Using Turtle/highscore.txt b/Snake Game Using Turtle/highscore.txt index 62f9457511f..1e8b3149621 100644 --- a/Snake Game Using Turtle/highscore.txt +++ b/Snake Game Using Turtle/highscore.txt @@ -1 +1 @@ -6 \ No newline at end of file +6 diff --git a/Snake Game Using Turtle/main.py b/Snake Game Using Turtle/main.py index 9b874f1a3df..7656b574656 100644 --- a/Snake Game Using Turtle/main.py +++ b/Snake Game Using Turtle/main.py @@ -3,6 +3,7 @@ It handles screen setup, dynamic boundaries, UI controls (buttons), game state management, and the main game loop. """ + from turtle import Screen, Turtle from snake import Snake from food import Food @@ -43,17 +44,18 @@ # --- UI CONTROLS (BUTTONS) --- buttons = {} # Dictionary to hold button turtles and their properties + def create_button(name, x, y, width=120, height=40): """Creates a turtle-based button with a label.""" - if name in buttons and buttons[name]['turtle'] is not None: - buttons[name]['turtle'].clear() + if name in buttons and buttons[name]["turtle"] is not None: + buttons[name]["turtle"].clear() button_turtle = Turtle() button_turtle.hideturtle() button_turtle.penup() button_turtle.speed("fastest") - button_turtle.goto(x - width/2, y - height/2) + button_turtle.goto(x - width / 2, y - height / 2) button_turtle.color(colors.BUTTON_BORDER_COLOR, colors.BUTTON_BG_COLOR) button_turtle.begin_fill() for _ in range(2): @@ -67,13 +69,22 @@ def create_button(name, x, y, width=120, height=40): button_turtle.color(colors.BUTTON_TEXT_COLOR) button_turtle.write(name, align="center", font=("Lucida Sans", 14, "bold")) - buttons[name] = {'turtle': button_turtle, 'x': x, 'y': y, 'w': width, 'h': height, 'visible': True} + buttons[name] = { + "turtle": button_turtle, + "x": x, + "y": y, + "w": width, + "h": height, + "visible": True, + } + def hide_button(name): """Hides a button by clearing its turtle.""" - if name in buttons and buttons[name]['visible']: - buttons[name]['turtle'].clear() - buttons[name]['visible'] = False + if name in buttons and buttons[name]["visible"]: + buttons[name]["turtle"].clear() + buttons[name]["visible"] = False + def manage_buttons(): """Shows or hides buttons based on the current game state.""" @@ -93,6 +104,7 @@ def manage_buttons(): elif game_state == "game_over": create_button("Restart", btn_x, btn_y) + # --- GAME LOGIC & STATE TRANSITIONS --- def start_game(): global game_state @@ -100,6 +112,7 @@ def start_game(): game_state = "playing" scoreboard.update_scoreboard() + def toggle_pause_resume(): global game_state if game_state == "playing": @@ -109,6 +122,7 @@ def toggle_pause_resume(): game_state = "playing" scoreboard.update_scoreboard() + def restart_game(): global game_state if game_state == "game_over": @@ -117,14 +131,18 @@ def restart_game(): food.refresh(LEFT_WALL, RIGHT_WALL, BOTTOM_WALL, TOP_WALL) scoreboard.reset() + def is_click_on_button(name, x, y): """Checks if a click (x, y) is within the bounds of a visible button.""" - if name in buttons and buttons[name]['visible']: + if name in buttons and buttons[name]["visible"]: btn = buttons[name] - return (btn['x'] - btn['w']/2 < x < btn['x'] + btn['w']/2 and - btn['y'] - btn['h']/2 < y < btn['y'] + btn['h']/2) + return ( + btn["x"] - btn["w"] / 2 < x < btn["x"] + btn["w"] / 2 + and btn["y"] - btn["h"] / 2 < y < btn["y"] + btn["h"] / 2 + ) return False + def handle_click(x, y): """Main click handler to delegate actions based on button clicks.""" if game_state == "start" and is_click_on_button("Play", x, y): @@ -136,24 +154,32 @@ def handle_click(x, y): elif game_state == "game_over" and is_click_on_button("Restart", x, y): restart_game() + # --- KEYBOARD HANDLERS --- def handle_snake_up(): if game_state in ["start", "playing"]: start_game() snake.up() + + def handle_snake_down(): if game_state in ["start", "playing"]: start_game() snake.down() + + def handle_snake_left(): if game_state in ["start", "playing"]: start_game() snake.left() + + def handle_snake_right(): if game_state in ["start", "playing"]: start_game() snake.right() + # --- KEY & MOUSE BINDINGS --- screen.listen() screen.onkey(handle_snake_up, "Up") @@ -165,6 +191,7 @@ def handle_snake_right(): screen.onkey(restart_game, "R") screen.onclick(handle_click) + # --- MAIN GAME LOOP --- def game_loop(): global game_state @@ -176,7 +203,10 @@ def game_loop(): snake.extend() scoreboard.increase_score() # Collision with wall - if not (LEFT_WALL < snake.head.xcor() < RIGHT_WALL and BOTTOM_WALL < snake.head.ycor() < TOP_WALL): + if not ( + LEFT_WALL < snake.head.xcor() < RIGHT_WALL + and BOTTOM_WALL < snake.head.ycor() < TOP_WALL + ): game_state = "game_over" scoreboard.game_over() # Collision with tail @@ -188,8 +218,8 @@ def game_loop(): screen.update() screen.ontimer(game_loop, MOVE_DELAY_MS) + # --- INITIALIZE GAME --- scoreboard.display_start_message() game_loop() screen.exitonclick() - diff --git a/Snake Game Using Turtle/scoreboard.py b/Snake Game Using Turtle/scoreboard.py index 4ca9265071c..840b2e7038e 100644 --- a/Snake Game Using Turtle/scoreboard.py +++ b/Snake Game Using Turtle/scoreboard.py @@ -2,6 +2,7 @@ This file manages the display of the score, high score, and game messages. It now positions the score dynamically in the top-left corner. """ + from turtle import Turtle, Screen import colors @@ -11,8 +12,10 @@ MESSAGE_FONT = ("Courier", 40, "bold") INSTRUCTION_FONT = ("Lucida Sans", 16, "normal") + class Scoreboard(Turtle): - """ This class maintains the scoreboard, high score, and game messages. """ + """This class maintains the scoreboard, high score, and game messages.""" + def __init__(self): super().__init__() self.screen = Screen() # Get access to the screen object @@ -38,7 +41,11 @@ def update_scoreboard(self): x_pos = -self.screen.window_width() / 2 + 30 y_pos = self.screen.window_height() / 2 - 60 self.goto(x_pos, y_pos) - self.write(f"Score: {self.score} | High Score: {self.high_score}", align=ALIGNMENT, font=SCORE_FONT) + self.write( + f"Score: {self.score} | High Score: {self.high_score}", + align=ALIGNMENT, + font=SCORE_FONT, + ) def increase_score(self): """Increases score and updates the display.""" @@ -60,7 +67,9 @@ def game_over(self): self.color(colors.GAME_OVER_COLOR) self.write("GAME OVER", align="center", font=MESSAGE_FONT) self.goto(0, -40) - self.write("Click 'Restart' or Press 'R'", align="center", font=INSTRUCTION_FONT) + self.write( + "Click 'Restart' or Press 'R'", align="center", font=INSTRUCTION_FONT + ) def display_pause(self): """Displays the PAUSED message.""" @@ -68,13 +77,18 @@ def display_pause(self): self.color(colors.MESSAGE_COLOR) self.write("PAUSED", align="center", font=MESSAGE_FONT) self.goto(0, -40) - self.write("Click 'Resume' or Press 'Space'", align="center", font=INSTRUCTION_FONT) - + self.write( + "Click 'Resume' or Press 'Space'", align="center", font=INSTRUCTION_FONT + ) + def display_start_message(self): """Displays the welcome message and starting instructions.""" self.goto(0, 40) self.color(colors.MESSAGE_COLOR) self.write("SNAKE GAME", align="center", font=MESSAGE_FONT) self.goto(0, -40) - self.write("Click 'Play' or an Arrow Key to Start", align="center", font=INSTRUCTION_FONT) - + self.write( + "Click 'Play' or an Arrow Key to Start", + align="center", + font=INSTRUCTION_FONT, + ) diff --git a/Snake Game Using Turtle/snake.py b/Snake Game Using Turtle/snake.py index e9fb153c317..70e7b02200d 100644 --- a/Snake Game Using Turtle/snake.py +++ b/Snake Game Using Turtle/snake.py @@ -2,6 +2,7 @@ This file is responsible for creating the snake and managing its movement, extension, and reset functionality. """ + from turtle import Turtle import colors @@ -9,21 +10,23 @@ MOVE_DISTANCE = 20 UP, DOWN, LEFT, RIGHT = 90, 270, 180, 0 + class Snake: - """ This class creates a snake body and contains methods for movement and extension. """ + """This class creates a snake body and contains methods for movement and extension.""" + def __init__(self): self.segments = [] self.create_snake() self.head = self.segments[0] def create_snake(self): - """ Creates the initial snake body. """ + """Creates the initial snake body.""" for position in STARTING_POSITIONS: self.add_segment(position) self.segments[0].color(colors.FIRST_SEGMENT_COLOR) def add_segment(self, position): - """ Adds a new segment to the snake. """ + """Adds a new segment to the snake.""" new_segment = Turtle(shape="square") new_segment.penup() new_segment.goto(position) @@ -31,12 +34,12 @@ def add_segment(self, position): self.segments.append(new_segment) def extend(self): - """ Adds a new segment to the snake's tail. """ + """Adds a new segment to the snake's tail.""" self.add_segment(self.segments[-1].position()) self.segments[0].color(colors.FIRST_SEGMENT_COLOR) def move(self): - """ Moves the snake forward by moving each segment to the position of the one in front.""" + """Moves the snake forward by moving each segment to the position of the one in front.""" for i in range(len(self.segments) - 1, 0, -1): x = self.segments[i - 1].xcor() y = self.segments[i - 1].ycor() @@ -70,4 +73,3 @@ def right(self): """Turns the snake's head to the right, preventing it from reversing.""" if self.head.heading() != LEFT: self.head.setheading(RIGHT) - diff --git a/Snake Game Using Turtle/wall.py b/Snake Game Using Turtle/wall.py index dc47848961b..b99d9704782 100644 --- a/Snake Game Using Turtle/wall.py +++ b/Snake Game Using Turtle/wall.py @@ -3,8 +3,10 @@ from turtle import Turtle, Screen import colors + class Wall: - """ This class creates a wall around the game screen that adjusts to its dimensions. """ + """This class creates a wall around the game screen that adjusts to its dimensions.""" + def __init__(self): self.screen = Screen() self.create_wall() @@ -43,4 +45,3 @@ def create_wall(self): wall.goto(right - 10, top - 70) self.screen.update() - diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py index 3928079b997..94c927feb0b 100644 --- a/Snake_water_gun/main.py +++ b/Snake_water_gun/main.py @@ -81,7 +81,7 @@ class bcolors: i += 1 print(f"{10 - i} matches left") -if run == True: +if run: print(f"Your score is {score} and the final result is...") time.sleep(3) if score > 5: diff --git a/Sorting Algorithims/mergesort_linkedlist.py b/Sorting Algorithims/mergesort_linkedlist.py index 4e833dc2e29..8e2a4831509 100644 --- a/Sorting Algorithims/mergesort_linkedlist.py +++ b/Sorting Algorithims/mergesort_linkedlist.py @@ -18,7 +18,7 @@ def insert(self, new_data: int) -> None: def printLL(self) -> None: temp = self.head - if temp == None: + if temp is None: return "Linked List is empty" while temp.next: print(temp.data, "->", end="") diff --git a/Sorting Algorithims/quicksort_linkedlist.py b/Sorting Algorithims/quicksort_linkedlist.py index 70804343a98..0e82636b651 100644 --- a/Sorting Algorithims/quicksort_linkedlist.py +++ b/Sorting Algorithims/quicksort_linkedlist.py @@ -26,7 +26,7 @@ def insert(self, new_data: int) -> None: # method to print the linkedlist def printLL(self) -> None: temp = self.head - if temp == None: + if temp is None: return "Linked List is empty" while temp.next: print(temp.data, "->", end="") @@ -39,7 +39,7 @@ def printLL(self) -> None: def partition(start, end): - if start == None or start.next == None: + if start is None or start.next is None: return start prev, curr = start, start.next pivot = prev.data diff --git a/Sorting Algorithms/Heap sort.py b/Sorting Algorithms/Heap sort.py index 6e5a80c3aff..2719cfa8875 100644 --- a/Sorting Algorithms/Heap sort.py +++ b/Sorting Algorithms/Heap sort.py @@ -1,5 +1,6 @@ # Python program for implementation of heap Sort + # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): diff --git a/Sorting Algorithms/Iterative Merge Sort.py b/Sorting Algorithms/Iterative Merge Sort.py index 734cf1954c0..4ec479dc7d1 100644 --- a/Sorting Algorithms/Iterative Merge Sort.py +++ b/Sorting Algorithms/Iterative Merge Sort.py @@ -1,5 +1,6 @@ # Iterative Merge sort (Bottom Up) + # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(a): diff --git a/Sorting Algorithms/brickSort.py b/Sorting Algorithms/brickSort.py index 08308d05a5a..a81f690288b 100644 --- a/Sorting Algorithms/brickSort.py +++ b/Sorting Algorithms/brickSort.py @@ -7,7 +7,6 @@ def oddEvenSort(arr, n): isSorted = 0 while isSorted == 0: isSorted = 1 - temp = 0 for i in range(1, n - 1, 2): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] diff --git a/Street_Fighter/src/fighter.py b/Street_Fighter/src/fighter.py index 94fc68abd16..b41c828b80a 100644 --- a/Street_Fighter/src/fighter.py +++ b/Street_Fighter/src/fighter.py @@ -55,7 +55,7 @@ def move(self, screen_width, screen_height, target, round_over): key = pygame.key.get_pressed() # can only perform other actions if not currently attacking - if self.attacking == False and self.alive == True and round_over == False: + if not self.attacking and self.alive and not round_over: # check player 1 controls if self.player == 1: # movement @@ -66,7 +66,7 @@ def move(self, screen_width, screen_height, target, round_over): dx = SPEED self.running = True # jump - if key[pygame.K_w] and self.jump == False: + if key[pygame.K_w] and not self.jump: self.vel_y = -30 self.jump = True # attack @@ -88,7 +88,7 @@ def move(self, screen_width, screen_height, target, round_over): dx = SPEED self.running = True # jump - if key[pygame.K_UP] and self.jump == False: + if key[pygame.K_UP] and not self.jump: self.vel_y = -30 self.jump = True # attack diff --git a/Trending youtube videos b/Trending youtube videos index a14535e4ddc..e74f15e75f3 100644 --- a/Trending youtube videos +++ b/Trending youtube videos @@ -1,43 +1,45 @@ -''' - Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos. +""" + Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos. You’ll need to have an API key from Google Cloud Platform to use the YouTube Data API. -First, install the google-api-python-client library if you haven’t already: +First, install the google-api-python-client library if you haven’t already: pip install google-api-python-client -Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles, -channels, and view counts of the top 10 trending YouTube videos in India. +Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles, +channels, and view counts of the top 10 trending YouTube videos in India. You can change the regionCode to any other country code if needed. Then, you can use the following code: -''' +""" from googleapiclient.discovery import build # Replace with your own API key -API_KEY = 'YOUR_API_KEY' -YOUTUBE_API_SERVICE_NAME = 'youtube' -YOUTUBE_API_VERSION = 'v3' +API_KEY = "YOUR_API_KEY" +YOUTUBE_API_SERVICE_NAME = "youtube" +YOUTUBE_API_VERSION = "v3" + def get_trending_videos(): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY) - + # Call the API to get the top 10 trending videos request = youtube.videos().list( - part='snippet,statistics', - chart='mostPopular', - regionCode='IN', # Change this to your region code - maxResults=10 + part="snippet,statistics", + chart="mostPopular", + regionCode="IN", # Change this to your region code + maxResults=10, ) response = request.execute() - + # Print the video details - for item in response['items']: - title = item['snippet']['title'] - channel = item['snippet']['channelTitle'] - views = item['statistics']['viewCount'] - print(f'Title: {title}\nChannel: {channel}\nViews: {views}\n') + for item in response["items"]: + title = item["snippet"]["title"] + channel = item["snippet"]["channelTitle"] + views = item["statistics"]["viewCount"] + print(f"Title: {title}\nChannel: {channel}\nViews: {views}\n") + -if __name__ == '__main__': +if __name__ == "__main__": get_trending_videos() diff --git a/Triplets with zero sum/find_Triplets_with_zero_sum.py b/Triplets with zero sum/find_Triplets_with_zero_sum.py index f88c6538a15..69699577df5 100644 --- a/Triplets with zero sum/find_Triplets_with_zero_sum.py +++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py @@ -50,7 +50,7 @@ def find_Triplets_with_zero_sum(arr, num): else: right -= 1 - if found == False: + if not found: print(" No Triplet Found") diff --git a/VoiceAssistant/Project_Basic_struct/TextTospeech.py b/VoiceAssistant/Project_Basic_struct/TextTospeech.py index 2bcc7f29b39..4755c96bec2 100644 --- a/VoiceAssistant/Project_Basic_struct/TextTospeech.py +++ b/VoiceAssistant/Project_Basic_struct/TextTospeech.py @@ -2,9 +2,7 @@ def tts(): - audio = "speech.mp3" - language = "en" sentence = input("Enter the text to be spoken :- ") speaker = win32com.client.Dispatch("SAPI.SpVoice") - sp = speaker.Speak(sentence) + speaker.Speak(sentence) diff --git a/VoiceAssistant/Project_Basic_struct/textRead.py b/VoiceAssistant/Project_Basic_struct/textRead.py index bd0d147121b..0a9fc41069f 100644 --- a/VoiceAssistant/Project_Basic_struct/textRead.py +++ b/VoiceAssistant/Project_Basic_struct/textRead.py @@ -43,7 +43,9 @@ def pdf_read(): path = doubleslash(location) pdf = fitz.open(path) - details = pdf.metadata # Stores the meta-data which generally includes Author name and Title of book/document. + details = ( + pdf.metadata + ) # Stores the meta-data which generally includes Author name and Title of book/document. total_pages = pdf.pageCount # Stores the total number of pages except Exception as exp: @@ -54,10 +56,10 @@ def pdf_read(): ) return "None" try: - """ 1. Author - 2. Creator - 3. Producer - 4. Title """ + """1. Author + 2. Creator + 3. Producer + 4. Title""" author = details["author"] # print("Author : ",author) @@ -181,7 +183,7 @@ def pdf_read(): try: key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) - if start_pg_no != None and end_pg_no != None: + if start_pg_no is not None and end_pg_no is not None: start_pg_no, end_pg_no = map( int, search_in_toc(toc, key, total_pages) ) @@ -199,7 +201,7 @@ def pdf_read(): start_pg_no, end_pg_no = map( int, search_in_toc(toc, key, total_pages) ) - if start_pg_no != None and end_pg_no != None: + if start_pg_no is not None and end_pg_no is not None: for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) text = page.get_text("text") @@ -212,7 +214,7 @@ def pdf_read(): speak("Lesson name") key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) - if start_pg_no != None and end_pg_no != None: + if start_pg_no is not None and end_pg_no is not None: start_pg_no, end_pg_no = map( int, search_in_toc(toc, key, total_pages) ) diff --git a/WeatherGUI.py b/WeatherGUI.py index 62a2fef6bf8..799f714f79a 100644 --- a/WeatherGUI.py +++ b/WeatherGUI.py @@ -1,10 +1,13 @@ import tkinter as tk import requests from bs4 import BeautifulSoup + url = "https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8" root = tk.Tk() root.title("Weather") root.config(bg="white") + + def getWeather(): page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") diff --git a/Web Socket.py b/Web Socket.py index 9c3c91beafa..8da7e224c00 100644 --- a/Web Socket.py +++ b/Web Socket.py @@ -1,5 +1,6 @@ # Program to print a data & it's Metadata of online uploaded file using "socket". import socket + skt_c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) skt_c.connect(("data.pr4e.org", 80)) link = "GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n".encode() diff --git a/XML/HTML parsing b/XML/HTML parsing index 8d8c2825e02..82876490f78 100644 --- a/XML/HTML parsing +++ b/XML/HTML parsing @@ -1,21 +1,22 @@ -dinner_recipe = '''
| amt | unit | item |
|---|---|---|
| 24 | slices | baguette |
| 2+ | tbsp | olive oil |
| 1 | cup | tomatoes |
| 1 | jar | pesto |