Posts

Showing posts from January, 2023

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

Find Largest and Smallest numbers Among User Input Numbers

Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. largest = None smallest = None while True :     try :         num = input ( "Enter a number: " )         if num == "done" :             break         num = int ( num )         if largest is None :             largest = num         elif num > largest :             largest = num         if smallest is None :             smallest = num         elif num < smallest :             smallest = num     except :         print ( "Invalid input" ) print ( "Maximum is" , largest ) print ( "Minimum is" , smallest )

Find out the Largest and Smallest Number (separately) in a List

# largest number in a list largest_num = None numbers = [ 9 , 22 , 3 , 566 , 43 , 432 , 34 , 233 , 123 , 2223 , 67 , 3030 , 5 ] for number in numbers :     if largest_num is None :         largest_num = number     elif number > largest_num :         largest_num = number print ( "Largest number is" , largest_num ) # Smallest number in a list smallest_num = None numbers = [ 9 , 22 , 3 , 566 , 43 , 432 , 34 , 233 , 123 , 2223 , 67 , 3030 , 5 ] for number in numbers :     if smallest_num is None :         smallest_num = number     elif number < smallest_num :         smallest_num = number print ( "Smallest number is" , smallest_num )

Jarvis AI Assistant Python Script

import pyttsx3 #pip install pyttsx3 import datetime import speech_recognition as sr #pip install speechRecognition import wikipedia #pip install wikipedia import webbrowser # import pyaudio import os import random import smtplib engine = pyttsx3.init("sapi5") voices = engine.getProperty("voices") # print(voices) # print(voices[0].id) # print(voices[1].id) engine.setProperty("voice", voices[1].id) def speak(audio): engine.say(audio) engine.runAndWait() def greetMe(): hour = datetime.datetime.now().hour # print(hour) # print(type(hour)) if hour >= 0 and hour < 12: print("Good Morning!") speak("Good Morning!") elif hour >= 12 and hour < 18: print("Good Afternoon!") speak("Good Afternoon!") elif hour >= 18 and hour < 20: print("Good Evening!") speak("Good Evening!") else: print("

Text to Speech Conversion in Python through gtts module

# pip install gTTS to install the required module # gTTS is Google Text to Speech API from gtts import gTTS import os mytext = "hi, this is abdur rehmaan." mylanguage = "en" obj = gTTS ( text = mytext , lang = mylanguage , slow = False ) obj . save ( "hi.mp3" ) # saves the text as mp3 file os . system ( "hi.mp3" ) # play the converted mp3 file

Score Grading Program in Python

""" 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table: Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85. """ score = input ( "Enter the Score: " ) score = float ( score ) if score >= 0 and score <= 1 :     if score >= 0.9 :         print ( "A" )     elif score >= 0.8 :         print ( "B" )     elif score >= 0.7 :         print ( "C" )     elif score >= 0.6 :         print ( "D" )     elif score < 0.6 :         print ( "F" ) else :     print ( "Score should be between 0.0 and 1.0" )

Jumbled Funny Names Exercise in Python

import random friendsNums = int ( input ( "Enter number of friends: " )) friendsList =[] for i in range ( friendsNums ):     names = input ( f "Emter the name of friend { i + 1 } : " )     friendsList . append ( names )     # print(friendsList) lastNames =[] firstNames =[] for friend in friendsList :     nameParts = friend .split( " " )     lastNames . append ( nameParts [ 1 ])     firstNames . append ( nameParts [ 0 ]) print ( " \n Your new funny names are: \n " ) for firstname in firstNames :     lastname = random . choice ( lastNames )     lastNames . remove ( lastname )     print ( firstname , lastname ) print ( " \n " )

Overtime Pay Calculation in Python

  hrs = float ( input ( "Enter hours: " )) rt = float ( input ( "Enter rate/h: " )) if hrs > 40 :     overtime = hrs - 40     overpay = overtime *( rt * 1.5 )     payof40hrs = rt * 40     pay = payof40hrs + overpay     else :     pay = rt * hrs     print ( "Pay:" , pay ) # The same thing in function format def computepay ( hrs , rt ):     if hrs > 40 :         overtime = hrs - 40         overpay = overtime *( rt * 1.5 )         payof40hrs = rt * 40         pay = payof40hrs + overpay     else :         pay = rt * hrs     return pay hrs = float ( input ( "Enter hours: " )) rt = float ( input ( "Enter rate/h: " )) print ( "Pay" , computepay ( hrs , rt ))

Map(), Filter() and Reduce() - Higher Order Functions

 Basically, all these high-order functions apply a function to an iterable. from functools import reduce def square ( n ): return n ** 2 def greaterThan ( n ): return n > 2 def addAll ( n , m ): return n + m mylist =[ 1 , 2 , 3 , 4 , 5 ] print ( list ( map ( square , mylist ))) print ( list ( filter ( greaterThan , mylist ))) print ( reduce ( addAll , mylist ))

Creating Python Virtual Environment in Windows

In the terminal of your python IDE or windows PowerShell, enter the command to install virtual environment. pip install virtualenv Now you can check whether the environment is successfully installed and also check its version virtualenv --version Now create a virtual environment with your chosen name. virtualenv yourvirtenvname Now activate your virtual environment. .\yourvirtenvname\Scripts\activate You can enter python by entering; python And exit python by entering; exit() Install packages in your virtual environment by using; pip install packagename To install a specific version of a package; pip install packagename==1.1.1 To check the version of your installed package; print(packagename.__version__) To see what packages are installed in the environment; pip freeze To come out of the environment, enter deactivate  To export all the installed packages (in a virtual environment) names along with their versions in a text file;  pip freeze > requirements.txt Then to install all thos

Else with For Loop in Python

Else is executed only if For loop completes successfully. for i in range(5): print(i) # if i==3: # break else: print("No answer")

Printing a month calendar in Python

All you need to do to print a month calendar in python. import calendar print(calendar.month(2023, 1)) # .month takes two arguments, year and month number

Functions and the various types of arguments they can take

This code snippet is about functions, its parameters and the various types of arguments a function can take. def funct(): print("I am a function that takes no value as input.") def country(countryname="Pakistan"): #parameter with default value print("The name of my country is", countryname) def greet(fname, lname): # fuction takes NMT and NLT 2 parameters print("Good evening", fname, lname) def person(*args): # accepts variable number of positional arguments print(args) # returns result with quotes, commas and brackets print(*args) # returns result without quotes, commas and brackets print(len(args)) # returns number of arguments given print(type(args)) # returns type of data which is tuple def personData(**kwargs): # accepts variable number of keyword arguments print(kwargs) # returns result with quotes, commas and brackets print(*kwargs) # returns only keys (without quotes, commas and brackets)

Try Except and Else block in Python

Try Except is a syntax for error handling in Python. Else block is optional and is executed only if program runs successfully without encountering any exception. a=40 b=10 try: c=a/b print(c) except: print("Cant divide by 0") else: print("Success")

Deleting a file in Python

We need os module to delete a file on hard drive import os if os.path.exists("myfile.txt"): os.remove("myfile.txt") print("Deleted successfully") else: print("No such file exists")

Copying contents of one file into another file in Python

File handling in Python try: with open("myfile.txt", "r") as f1: with open("newfile.txt", "w") as f2: for i in f1: # print(type(f2)) f2.write(i) except: print("Sorry! The file does not exist. Plz create first.") else: print("Contents of file copied successfully.")

Generating Random Alphabet in Python

There are two ways to generate a random alphabet in python. The first method uses string and random modules. import string import random randomAlphabet = random.choice(string.ascii_letters) print(randomAlphabet) The second method uses random module only. import random randomCharacter = chr(random.randint(ord("a"), ord("z"))) print(randomCharacter)

Program to Encode or Decode a Secret Message in Python

Enter your message and the following program will encode or encrypt it. Also it can decode or decrypt your message. import random rc1 = chr(random.randint(ord("a"), ord("z"))) rc2 = chr(random.randint(ord("a"), ord("z"))) rc3 = chr(random.randint(ord("a"), ord("z"))) rc4 = chr(random.randint(ord("a"), ord("z"))) rc5 = chr(random.randint(ord("a"), ord("z"))) rc6 = chr(random.randint(ord("a"), ord("z"))) user_input = input("What you want to do?\n" "1. Encode\n" "2. Decode\n>>> ") user_input = eval(user_input) if user_input == 1: toEncode = input("Enter the words you want to encode: ").split(" ") for word in toEncode: if len(word) < 3: print(word[::-1], end=" ") else: print(rc1+rc2+rc3+word[1:]+word[0]+rc4+rc5+rc6, end=" ")

Fraud Checker Program in Python

Rohan is a cheater who created a function to print multiplication tables for input numbers. We created a function that validates Rohan tables and tells whether Rohan is a fraud or not. Enjoy! # FRAUD Checker: This program checks whether Rohan Das is a fraud or not. # whether Rohan Das function returns the multiplication tables correctly or not import random def rohanTables(n): tabletList = [] for i in range(1, 11): randomNumber = random.randint(3,9) if i == randomNumber: result=(randomNumber*n) + random.randint(1, 4) else: result=i*n tabletList.append(result) return tabletList def validateRohandTables(n): tabletList = [] for i in range(1, 11): result=i*n tabletList.append(result) return tabletList whichTable = int(input("Which table do you want: ")) conclusions = [] for i in range(5): r = rohanTables(whichTable) print(r) v = validateRohandTables(whichTable) p

Python Quiz Game

Source code of Quiz Game in Python scoreList = [] def gameKBC(n): """Answer the questions asked correctly and win money""" questionslist = ["What is the capital city of Pakistan?", "What programming language has the most user-friendly syntax?", "What is the chemical composition of water?", "Stars are mainly made of?", "How old is our universe?"] optionsList = [["Peshawar", "Karachi", "Lahore", "Islamabad"], ["python", "c++", "java", "lisp"], ["hydrogen", "oxygen", "hydrogen and oxygen", "nitrogen"], ["helium", "hydrogen", "iron", "chromium"], ["6000 years", "10,000 years", "1M years", ">