Posts

Showing posts with the label python

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

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)

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)

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

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