Posts

Showing posts with the label coding

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)

Decorators in Python

def greet(fx): # decorator function def mfx(*args, **kwargs): print("Welcome to this function!") fx(*args, **kwargs) print("Thanks for using this function.") return mfx @greet def add(a,b): print("The sum of your numbers is", a+b) @greet def thisWorld(): print("This world is beautiful.") # add(2,4) # print() # just to print a new line or blank line # thisWorld() # the above decorators can also be implemented in the following way... greet(thisWorld()) # == greet(thisWorld)() greet(add(3,4)) # == greet(add)(3,4)

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

Interest Payment Calculator in Python

loan = float(input("How much loan do you want? ")) duration = float(input("In how many months will you return this loan? ")) interest_rate = loan / 100 * 2 #2 pc interest for 1 month loan print(f"You took a loan of {loan} ruppees for {duration} month(s) duration.") print(f"After {duration} month(s), you will pay us {loan+interest_rate*duration} ruppees.") monthly_payment = round((loan+interest_rate*duration)/duration, 3) print(f"On monthly basis, you can pay us {monthly_payment}") # you can replace the above two lines with the following... and it will work the same # monthly_payment = (loan+interest_rate*duration)/duration # print("On a monthly basis, you can pay us %.2f" % monthly_payment)

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

Binary Search Algorithm in Python

Binary Search has less time complexity as compared to linear search. In linear search, potentially all the members are checked while in binary search case, chunks of data are dropped where the target element is not there according to the conditions in the program. def binarySearch(mylist, target): start = 0 # index of 1st element in list end = len(mylist)-1 # index of last element in list step = 0 # binary search operation step while start<=end: if target not in mylist: print(f"Sorry the value {target} is not found in the list.") return print("At step:",step,"The list is",mylist[start:end+1]) step += 1 middle = (start + end) // 2 if target == mylist[middle]: print(f"Your target value which is {target} is found in the list at index {middle}") return elif target < mylist[middle]:

Email Slicer in Python

a = input ( "Plz enter your email address: " ) b , c = a . split ( "@" ) d , e = c . split ( "." ) print ( "The username is" , b ) print ( "The domain is" , d ) print ( "The extension is" , e )  

Sending Email in Python

2 Methods (One via SSL port, other via TLS port) # Method 1 from email.message import EmailMessage import ssl import smtplib sender_email = input("Plz enter your email address: ") email_password = input("Plz enter your password: ") receiver_email = input("Plz enter the recipient email address: ") subject = input("Plz enter the subject of your email: ") body = input("Plz enter the message of your email: ") myemail = EmailMessage() myemail['From'] = sender_email myemail['To'] = receiver_email myemail['subject'] = subject myemail.set_content(body) context = ssl.create_default_context() with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp: smtp.login(sender_email, email_password) smtp.sendmail(sender_email, receiver_email, myemail.as_string()) # Method 2 import smtplib # default Gmail SMTP server name is smtp.gmail.com # secure SMTP Gmail ports are 465 (SSL required) and 587 (T