Posts

Showing posts with the label Abdur Codes

Working with OS module in Python

import os def soldier(a,b,c): os.chdir(a) i = 1 items = os.listdir(a) for item in items: if item.endswith(b): os.rename(item, item.capitalize()) if item.endswith(c): os.rename(item, f"{i}.{c}") i += 1 fpath = r"D:\abdur codes\space\thisisit\fffffffffffffffff" filename = ".py" format = ".png" soldier(fpath, filename, format) ###################################################################### import os def soldier(fpath, filename, format): os.chdir(fpath) i = 1 files = os.listdir(fpath) with open(filename) as f: # this file contains files names which we will not tamper with filelist = f.read().split("\n") for file in files: if file not in filelist: os.rename(file, file.capitalize()) # if os.splitext(fpath)[1]==format: if os.path.splitext(fil

Command Line Utility of a Faulty Calculator

import argparse import sys def calc(args): if args.o == "+": if (args.a == 56 and args.b == 9) or (args.a == 9 and args.b == 56): return 77.0 else: return args.a + args.b elif args.o == "-": return args.a - args.b elif args.o == "*": if (args.a == 45 and args.b == 3) or (args.a == 3 and args.b == 45): return 555.0 else: return args.a * args.b elif args.o == "/": if args.a == 56 and args.b == 6: return 4.0 else: return args.a / args.b else: return "Something went wrong. Try again!" parser = argparse.ArgumentParser() parser.add_argument("--a", type=float, default=1, help="Enter your first number plz") parser.add_argument("--b", type=float, default=0, help="Enter your second number plz") parser.add_argument("--o", type=str, defaul

Python Puzzle Game

This code implements a simple puzzle game using the Pygame library. It loads a background image and puzzle piece images, creates a 3x3 grid of puzzle pieces, and allows the player to click and drag pieces to swap them. The game checks if the puzzle is solved after each move, and displays a congratulatory message if the puzzle is solved. Here's a brief summary of the code: The Pygame library is imported and initialized. The game window is set up with a width of 483 pixels and a height of 480 pixels, and a caption of "Make Abdur - Puzzle Game". The background music and sound effects are loaded from sound files. The puzzle piece images are loaded from files and stored in a list called pieces. The game loop starts, which repeatedly draws the background image and puzzle pieces on the screen and waits for user input. User input is handled using Pygame's event handling system. Specifically, the game listens for QUIT, MOUSEBUTTONDOWN, MOUSEBUTTONUP, and MOUSEMOTION events. Wh

Command Line Arguments in Python

Open the following as this in cmd: python filename.py argument from sys import argv if len(argv) == 2: print(f"Hello, {argv[1]}!") else: print("Hello, World!") # to see what is there in argv for arg in argv: print(arg)

Extract Tables from a Web Page in Python

import pandas as pd xfiles = pd.read_html("https://en.wikipedia.org/wiki/List_of_The_X-Files_episodes") print(xfiles) # prints all the tables on the page as list print(type(xfiles)) print(len(xfiles)) print(xfiles[1]) # table of season 1 print(xfiles[12]) # table of season 10

Read CSV from a Web Page

import pandas as pd # the link is taken from right-clicking the csv file on a web page and 'copy link address' footballData = pd.read_csv("https://datahub.io/sports-data/english-premier-league/r/season-1819.csv") # print(footballData) # renaming two columns names; the inplace changes the original footballData.rename(columns={"FTHG": "Home", "FTAG": "Abroad"}, inplace=True) print(footballData)

Plotting Graphs in Python with Matplotlib Library

import matplotlib.pyplot as plt # one line graph plotting x = [1,2,3,4,5] y = [320, 400, 650, 456, 870] plt.plot(x,y) # customizing your graph # plt.plot( # x, y, color="red", linestyle="dashed", # linewidth=2, marker="o", markerfacecolor="cyan", # markersize=14 # ) # plt.xlim(1,10) # x axis limits # plt.ylim(1,1000) # y axis limits plt.xlabel("Months") plt.ylabel("Gas Bills") plt.title("Gas bills of the months") plt.show() ############################################ # two-lines graph plotting x1 = [1,2,3,4,5] y1 = [320, 400, 650, 456, 870] plt.plot(x1,y1, label="Gas Bills") x2 = [1,2,3,4,5] y2 = [620, 800, 450, 556, 270] plt.plot(x2,y2, label="Water Bills") plt.xlabel("Months") plt.ylabel("Billing Amount") plt.title("Bills of the months") plt.legend() plt.show() ############################################ # creating a bar chart player

Image Resizing Script in Python

from PIL import Image #pip install Pillow def resize_your_image(width, height): image_address = "new-img.jpg" image = Image.open(image_address) print("The original size of your image is",image.size) image_resize = image.resize((width, height)) print("Image successfully resized to",image_resize.size) image_resize.save(f"r-img-{image_resize.size}.jpg") print("Image successfully saved.") print("Welcome to Image Resizer!") width=int(input("Plz enter the required width: ")) height=int(input("Plz enter the required height: ")) resize_your_image(width, height)

Scraping Post Titles from a Blog Page in Python

import requests #pip install requests from bs4 import BeautifulSoup #pip install beautifulsoup4 url = "https://www.pharmacymcqs.com/" resposne = requests.get(url) # print(resposne) soup = BeautifulSoup(resposne.content, "lxml") # print(soup) post_titles = soup.find_all("h2", {"class":"post-title"}) # to print only the first title # print(post_titles[0].getText()) # to print all the titles from the blog page for title in post_titles: print(title.getText())

Send Scheduled SMS in Python - Python Automation

import schedule import requests def send_auto_message(): resp = requests.post('https://textbelt.com/text', { 'phone': "yourPhoneNumber", 'message': 'Your message goes here', 'key': "YourAPIKey"}) print(resp.json()) # prints the status # send_auto_message() # the task is scheduled for everyday in the morning at 6:00 schedule.every().day.at("06:00").do(send_auto_message) # practice schedule with a simple function def this(): print("I am the scheduled task.") schedule.every(2).seconds.do(this) while True: schedule.run_pending()

Face Detection Script in Python

Method # 1 import cv2 #pip install opencv-python import pathlib # take the cascade file for frontal face detection cascade_path = pathlib.Path(cv2.__file__).parent.absolute()/"data/haarcascade_frontalface_default.xml" # print(cascade_path) # training classifier on the cascade file clf = cv2.CascadeClassifier(str(cascade_path)) # face detection in camera camera = cv2.VideoCapture(0) # 0 is for default camera # face detection in video # camera = cv2.VideoCapture("cud.mp4") while True: _, frame = camera.read() # _ ignores the first return value # some Python functions return multiple values, often we don’t need all of them. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = clf.detectMultiScale( gray, scaleFactor = 1.1, minNeighbors=5, # higher this number, less faces are found minSize = (30, 30), # size of window flags = cv2.CASCADE_SCALE_IMAGE)

Implementing Real-World English Dictionary in Python

# pip install Py-Dictionary from pydictionary import Dictionary print("Welocme to the English Dictionary!") print("""What you want to know? A- Meanings B- Synonyms C- Antonyms""") option = input("Plz enter your option: ").lower() if option == "a": word = input("Enter the word to know its meaning(s): ") dict = Dictionary(word, 2) dict.print_meanings("yellow") # yellow is for color of the printed text elif option == "b": word = input("Enter the word to know its synonym(s): ") dict = Dictionary(word, 3) dict.print_synonyms("blue") elif option == "c": word = input("Enter the word to know its antonym(s): ") dict = Dictionary(word, 4) dict.print_antonyms("green") else: print("Invalid input")

Creating Custom French-to-English Dictionary in Python

dictFrench = { "je": "I", "chat": "cat", "chien": "dog", "cheval": "horse", "femme": "woman", "fille": "girl", "homme": "man", "avec": "with", "elle": "she", "garcon": "boy", "bonjour": "Good Morning!", "salut": "hi" } print("\nWelcome to the cute little French-to-English Dictionary!") print("\nThis dictionary contains the following French words.") for word in dictFrench.keys(): print(word) while True: french_word = input("\nInput any French word to know its english meaning: ") if french_word in dictFrench.keys(): print(f"\'{french_word}\' is French for \'{dictFrench[french_word]}\'.") e

Leap Year Finder in Python

# a year is leap year if it is evenly divisble by 4 # a year is leap year if it is evenly divisible by 4 but may not by 100 # a year is leap year if it is evenly divisible by 4, by 100 as well as by 400 print("Welcome to Leap Year Finder!") while True: year = int(input("Plz enter the year: ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print(f"{year} is a Leap Year.") else: print(f"{year} is not a Leap Year.") else: print(f"{year} is a Leap Year.") else: print(f"{year} is not a Leap Year.")

Currency Converter from USD to PKR and vice versa in Python

print("Welcome to Currency Converter!") print("A- USD to PKR") print("B- PKR to USD") choice = input("Plz enter your choice: ").lower() if choice == "a": dollars = float(input("Plz enter the amount of dollars: ")) pkr = dollars * 261.17 print(f"{dollars} dollar(s) is equal to {round((pkr), 2)} Pakistani Rupees!") elif choice == "b": pkr = float(input("Plz enter the amount of rupees: ")) dollars = pkr / 261.17 print(f"{pkr} Rupee(s) is equal to {round((dollars), 2)} US dollars!") else: print("invalid input.")

Site Connectivity Checker Script in Python

import urllib.request as ur def site_connectivity_checker(url): print("Checking the status of the site", site_url) response = ur.urlopen(url) print("Successfully connected to", url) print("The status code of your website is",response.getcode()) print("This tool checks the status of your website") site_url = input("Plz input your website's url: ") site_connectivity_checker(site_url)

Dice Rolling Simulator Program in Python

import random dice_drawings = { 1: ("┌─────────┐", "│ │", "│ ● │", "│ │", "└─────────┘"), 2: ("┌─────────┐", "│ ● │", "│ │", "│ ● │", "└─────────┘"), 3: ("┌─────────┐", "│ ● │", "│ ● │", "│ ● │", "└─────────┘"), 4: ("┌─────────┐", "│ ● ● │", "│ │", "│ ● ● │", "└─────────┘"), 5: ("┌─────────┐", "│ ● ● │", "│ ● │", "│ ● ● │", "└─────────┘"), 6: ("┌─────────┐", "│ ● ● │", "│

Create "Suggest Strong Password" in Python

import string import random def suggest_strong_password(): characters = list(string.ascii_letters + string.digits + string.punctuation) # print(characters) # print(type(characters)) random.shuffle(characters) # print(characters) pass_length = int(input("How long your password should be? ")) password = [] for i in range(0, pass_length): password.append(random.choice(characters)) # print(password) random.shuffle(password) # print(password) final_password = "".join(password) print(final_password) suggest_strong_password()

Generate QR Code in Python

Generate QR code in python using "qrcode" library import qrcode # pip install qrcode data = "youtube.com/@computergeek7442" img = qrcode.make(data) img.save("myqrcode.png") # For more control use this method def qrcode_generate(data): # create an object of QRCode class qr = qrcode.QRCode( version=1, # controls the size of the QR Code (1 to 40) the smallest is version 1 error_correction = qrcode.constants.ERROR_CORRECT_L, # controls the error correction # four constants available on the qrcode package: # ERROR_CORRECT_L About 7% or less errors can be corrected # ERROR_CORRECT_M (default) About 15% or less errors can be corrected # ERROR_CORRECT_Q About 25% or less errors can be corrected # ERROR_CORRECT_H About 30% or less errors can be corrected box_size=10, border=4 # controls how many boxes thick the border should be (the default is 4, which is the minimum according to the

Python Quiz Program

Basic Python Quiz Program quiz = { "question1": { "question": "What is the capital city of Pakistan?", "answer": "Islamabad" }, "question2": { "question": "When Pakistan separated from India?", "answer": "1947" }, "question3": { "question": "What is the name of the tallest mountain in the world?", "answer": "Everest" }, "question4": { "question": "What is the name of the nearest planet to the sun?", "answer": "Mercury" }, "question5": { "question": "Our sun is a star? Yes or No?", "answer": "Yes" } } score = 0 for key, value in quiz.items(): print("") print(value["question"]) correctAnswer