Simple GUI calculator using Tkinter

from tkinter import *

expression = ""

def press(num):

global expression

expression = expression + str(num)

equation.set(expression)

def equalpress():

try:

global expression

total = str(eval(expression))

equation.set(total)

expression = ""

except:

equation.set(" error ")

expression = ""

def clear():

global expression

expression = ""

equation.set("")

if __name__ == "__main__":

gui = Tk()

gui.configure(background="light green")

gui.title("Simple Calculator")

gui.geometry("270x150")

equation = StringVar()

expression_field = Entry(gui, textvariable=equation)

expression_field.grid(columnspan=4, ipadx=70)

button1 = Button(gui, text=' 1 ', fg='black', bg='red',

command=lambda: press(1), height=1, width=7)

button1.grid(row=2, column=0)

button2 = Button(gui, text=' 2 ', fg='black', bg='red',

command=lambda: press(2), height=1, width=7)

button2.grid(row=2, column=1)

button3 = Button(gui, text=' 3 ', fg='black', bg='red',

command=lambda: press(3), height=1, width=7)

button3.grid(row=2, column=2)

button4 = Button(gui, text=' 4 ', fg='black', bg='red',

command=lambda: press(4), height=1, width=7)

button4.grid(row=3, column=0)

button5 = Button(gui, text=' 5 ', fg='black', bg='red',

command=lambda: press(5), height=1, width=7)

button5.grid(row=3, column=1)

button6 = Button(gui, text=' 6 ', fg='black', bg='red',

command=lambda: press(6), height=1, width=7)

button6.grid(row=3, column=2)

button7 = Button(gui, text=' 7 ', fg='black', bg='red',

command=lambda: press(7), height=1, width=7)

button7.grid(row=4, column=0)

button8 = Button(gui, text=' 8 ', fg='black', bg='red',

command=lambda: press(8), height=1, width=7)

button8.grid(row=4, column=1)

button9 = Button(gui, text=' 9 ', fg='black', bg='red',

command=lambda: press(9), height=1, width=7)

button9.grid(row=4, column=2)

button0 = Button(gui, text=' 0 ', fg='black', bg='red',

command=lambda: press(0), height=1, width=7)

button0.grid(row=5, column=0)

plus = Button(gui, text=' + ', fg='black', bg='red',

command=lambda: press("+"), height=1, width=7)

plus.grid(row=2, column=3)

minus = Button(gui, text=' - ', fg='black', bg='red',

command=lambda: press("-"), height=1, width=7)

minus.grid(row=3, column=3)

multiply = Button(gui, text=' * ', fg='black', bg='red',

command=lambda: press("*"), height=1, width=7)

multiply.grid(row=4, column=3)

divide = Button(gui, text=' / ', fg='black', bg='red',

command=lambda: press("/"), height=1, width=7)

divide.grid(row=5, column=3)

equal = Button(gui, text=' = ', fg='black', bg='red',

command=equalpress, height=1, width=7)

equal.grid(row=5, column=2)

clear = Button(gui, text='Clear', fg='black', bg='red',

command=clear, height=1, width=7)

clear.grid(row=5, column='1')

Decimal= Button(gui, text='.', fg='black', bg='red',

command=lambda: press('.'), height=1, width=7)

Decimal.grid(row=6, column=0)

gui.mainloop()


program to rotate doubly linked list by N nodes

class Node:    

    def __init__(self,data):    

        self.data = data;    

        self.previous = None;    

        self.next = None;    

class RotateList:    

    def __init__(self):    

        self.head = None;    

        self.tail = None;    

        self.size = 0;    

    def addNode(self, data):    

        newNode = Node(data);    

        if(self.head == None):    

            self.head = self.tail = newNode;    

            self.head.previous = None;    

            self.tail.next = None;    

        else:    

            self.tail.next = newNode;    

            newNode.previous = self.tail;    

            self.tail = newNode;    

            self.tail.next = None;    

        self.size = self.size + 1;    

    def rotateList(self, n):    

        current = self.head;    

        if(n == 0 or n >= self.size):    

            return;    

        else:   

            for i in range(1, n):    

                current = current.next;                  

            self.tail.next = self.head;    

            self.head = current.next;    

            self.head.previous = None;    

            self.tail = current;    

            self.tail.next = None;              

    def display(self):    

        current = self.head;    

        if(self.head == None):    

            print("List is empty");    

            return;                  

        while(current != None):    

            print(current.data),    

            current = current.next;    

        print();    

dList = RotateList();    

dList.addNode(1);    

dList.addNode(2);    

dList.addNode(3);    

dList.addNode(4);    

dList.addNode(5);    

print("Original List: ");    

dList.display();    

dList.rotateList(3);    

print("Updated List: ");    

dList.display();   


Program to display Zodiac sign for given date of birth

def zodiac_sign(day, month):

if month == 'december':

astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'

elif month == 'january':

astro_sign = 'Capricorn' if (day < 20) else 'aquarius'

elif month == 'february':

astro_sign = 'Aquarius' if (day < 19) else 'pisces'

elif month == 'march':

astro_sign = 'Pisces' if (day < 21) else 'aries'

elif month == 'april':

astro_sign = 'Aries' if (day < 20) else 'taurus'

elif month == 'may':

astro_sign = 'Taurus' if (day < 21) else 'gemini'

elif month == 'june':

astro_sign = 'Gemini' if (day < 21) else 'cancer'

elif month == 'july':

astro_sign = 'Cancer' if (day < 23) else 'leo'

elif month == 'august':

astro_sign = 'Leo' if (day < 23) else 'virgo'

elif month == 'september':

astro_sign = 'Virgo' if (day < 23) else 'libra'

elif month == 'october':

astro_sign = 'Libra' if (day < 23) else 'scorpio'

elif month == 'november':

astro_sign = 'scorpio' if (day < 22) else 'sagittarius'

print(astro_sign)

if __name__ == '__main__':

day = 19

month = "may"

zodiac_sign(day, month)


Color game using Tkinter

import tkinter

import random

colours = ['Red','Blue','Green','Pink','Black',

'Yellow','Orange','White','Purple','Brown']

score = 0

timeleft = 30

def startGame(event):

if timeleft == 30:

countdown()

nextColour()

def nextColour():

global score

global timeleft

if timeleft > 0:

e.focus_set()

if e.get().lower() == colours[1].lower():

score += 1

e.delete(0, tkinter.END)

random.shuffle(colours)

label.config(fg = str(colours[1]), text = str(colours[0]))

scoreLabel.config(text = "Score: " + str(score))

def countdown():

global timeleft

if timeleft > 0:

timeleft -= 1

timeLabel.config(text = "Time left: "

+ str(timeleft))

timeLabel.after(1000, countdown)

root = tkinter.Tk()

root.title("COLORGAME")

root.geometry("375x200")

instructions = tkinter.Label(root, text = "Type in the colour"

"of the words, and not the word text!",

font = ('Helvetica', 12))

instructions.pack()

scoreLabel = tkinter.Label(root, text = "Press enter to start",

font = ('Helvetica', 12))

scoreLabel.pack()


timeLabel = tkinter.Label(root, text = "Time left: " +

str(timeleft), font = ('Helvetica', 12))

timeLabel.pack()


label = tkinter.Label(root, font = ('Helvetica', 60))

label.pack()

e = tkinter.Entry(root)

root.bind('<Return>', startGame)

e.pack()

e.focus_set()

root.mainloop()


Write a python code to print this pattern.

 


def pattern(n):

num = 65

for i in range(0,n):

for j in range(0,i+1):

ch = chr(num)

print(ch,end = " ")

num = num + 1

print("\r")

n = 5

pattern(n)

Create a stopwatch using python

import tkinter as Tkinter

from datetime import datetime

counter = 66600

running = False

def counter_label(label):

def count():

if running:

global counter

if counter==66600:

display="Starting..."

else:

tt = datetime.fromtimestamp(counter)

string = tt.strftime("%H:%M:%S")

display=string


label['text']=display 

label.after(1000, count)

counter += 1

count()

def Start(label):

global running

running=True

counter_label(label)

start['state']='disabled'

stop['state']='normal'

reset['state']='normal'

def Stop():

global running

start['state']='normal'

stop['state']='disabled'

reset['state']='normal'

running = False

def Reset(label):

global counter

counter=66600

if running==False:

reset['state']='disabled'

label['text']='Welcome!'

else:

label['text']='Starting...'

root = Tkinter.Tk()

root.title("Stopwatch")

root.minsize(width=250, height=70)

label = Tkinter.Label(root, text="Welcome!", fg="black", font="Verdana 30 bold")

label.pack()

f = Tkinter.Frame(root)

start = Tkinter.Button(f, text='Start', width=6, command=lambda:Start(label))

stop = Tkinter.Button(f, text='Stop',width=6,state='disabled', command=Stop)

reset = Tkinter.Button(f, text='Reset',width=6, state='disabled', command=lambda:Reset(label))

f.pack(anchor = 'center',pady=5)

start.pack(side="left")

stop.pack(side ="left")

reset.pack(side="left")

root.mainloop()


program to find number of days between two given dates

class Date:

def __init__(self, d, m, y):

self.d = d

self.m = m

self.y = y

monthDays = [31, 28, 31, 30, 31, 30,

31, 31, 30, 31, 30, 31]

def countLeapYears(d):

years = d.y

if (d.m <= 2):

years -= 1

return int(years / 4) - int(years / 100) + int(years / 400)

def getDifference(dt1, dt2):

n1 = dt1.y * 365 + dt1.d

for i in range(0, dt1.m - 1):

n1 += monthDays[i]

n1 += countLeapYears(dt1)

n2 = dt2.y * 365 + dt2.d

for i in range(0, dt2.m - 1):

n2 += monthDays[i]

n2 += countLeapYears(dt2)

return (n2 - n1)

dt1 = Date(13, 12, 2018)

dt2 = Date(25, 2, 2019)

print(getDifference(dt1, dt2), "days")


Program to convert DateTime to string

import time

def convert(datetime_str):

datetime_str = time.mktime(datetime_str)

format = "%b %d %Y %r" 

dateTime = time.strftime(format, time.gmtime(datetime_str))

return dateTime

date_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0)

print(convert(date_time))


program to find Tuples with positive elements in List of tuples

test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]

print("The original list is : " + str(test_list))

res = [sub for sub in test_list if all(ele >= 0 for ele in sub)]

print("Positive elements Tuples : " + str(res))


Program to create infinity using turtle

from turtle import *

bgcolor("black")

color("yellow")

speed(11)

right(45)

for i in range(150):

circle(30)

if 7<i<62:

left(5)

if 80<i<133:

right(5)

if i<80:

forward(10)

else:

forward(5)

program to create a doubly linked list from a ternary tree

class Node:    

    def __init__(self,data):    

        self.data = data;    

        self.left = None;    

        self.middle = None;    

        self.right = None;    

class TernaryTreeToDLL:    

    def __init__(self):    

        self.root = None;    

        self.head = None;    

        self.tail = None;    

    def convertTernaryToDLL(self, node):    

        if(node == None):    

            return;    

        left = node.left;    

        middle = node.middle;    

        right = node.right;    

        if(self.head == None):    

            self.head = self.tail = node;    

            node.middle = None;    

            self.head.left = None;    

            self.tail.right = None;    

        else:    

            self.tail.right = node;    

            node.left = self.tail;    

            node.middle = None;    

            self.tail = node;    

            self.tail.right = None;    

        self.convertTernaryToDLL(left);    

        self.convertTernaryToDLL(middle);    

        self.convertTernaryToDLL(right);        

    def displayDLL(self):    

        current = self.head;    

        if(self.head == None):    

            print("List is empty");    

            return;    

        print("Nodes of generated doubly linked list: ");    

        while(current != None):    

            print(current.data),    

            current = current.right;    

tree = TernaryTreeToDLL();    

tree.root = Node(5);    

tree.root.left = Node(10);    

tree.root.middle = Node(12);    

tree.root.right = Node(15);    

tree.root.left.left = Node(20);    

tree.root.left.middle = Node(40);    

tree.root.left.right = Node(50);    

tree.root.middle.left = Node(24);    

tree.root.middle.middle = Node(36);    

tree.root.middle.right = Node(48);    

tree.root.right.left = Node(30);    

tree.root.right.middle = Node(45);    

tree.root.right.right = Node(60);    


tree.convertTernaryToDLL(tree.root);    

     

tree.displayDLL();

Program to write numbers 1 to 100 in a file

class File:

    def Create_file(self,fname):

        file = open(fname , 'w+')

        file.close()

        print("File Created as '{}'Successfully!\n".format(fname))


    def write_1__to_100(self,fname):

        try:

            fp = open(fname , 'w')

            for i in range(1,101):

                fp.write(str(i)+'\t')

            fp.close()

            print("\n Numbers written Successfully!")


        except FileNotFoundError:

            print('File not found')

if __name__ == '__main__':

    obj = File()

    k = 'C'

    while k=='C':

        ch = int(input("1.Create a File \n2.Write numbers 1 to 100 in file\nAny other key to Exit\n"))

        if ch==1:

            fname = input('Enter File name:')

            obj.Create_file(fname)

        elif ch==2:

            fname = input('Enter File name:')

            obj.write_1__to_100(fname)

        else:

            exit(0)

        k = input("Press 'C' to continue Other Key to exit:")

        print('\n')

else:

    pass

Heap Sort in Python

from heapq import heappop, heappush    

def heapsort(list1):  

     heap = []  

     for ele in list1:  

         heappush(heap, ele)    

     sort = []     

     while heap:  

         sort.append(heappop(heap))     

     return sort     

list1 = [27, 21, 55, 15, 60, 4, 11, 17, 2, 87]  

print(heapsort(list1))  

Bubble Sort in Python

def bubble_sort(list1):  

    for i in range(0,len(list1)-1):  

        for j in range(len(list1)-1):  

            if(list1[j]>list1[j+1]):  

                temp = list1[j]  

                list1[j] = list1[j+1]  

                list1[j+1] = temp  

    return list1  

list1 = [5, 3, 8, 6, 7, 2]  

print("The unsorted list is: ", list1)  

print("The sorted list is: ", bubble_sort(list1))  


Program to Find HCF(Highest Common Factor)

def calculate_hcf(x, y):  

    if x > y:  

        smaller = y  

    else:  

        smaller = x  

    for i in range(1,smaller + 1):  

        if((x % i == 0) and (y % i == 0)):  

            hcf = i  

    return hcf  

num1 = int(input("Enter first number: "))  

num2 = int(input("Enter second number: "))  

print("The H.C.F. of", num1,"and", num2,"is", calculate_hcf(num1, num2))  

program to create and display a doubly linked list

class Node:    

    def __init__(self,data):    

        self.data = data;    

        self.previous = None;    

        self.next = None;                

class DoublyLinkedList:    

    def __init__(self):    

        self.head = None;    

        self.tail = None;                

    def addNode(self, data):    

        newNode = Node(data);                

        if(self.head == None):    

            self.head = self.tail = newNode;    

            self.head.previous = None;    

            self.tail.next = None;    

        else:    

            self.tail.next = newNode;    

            newNode.previous = self.tail;    

            self.tail = newNode;    

            self.tail.next = None;                   

    def display(self):    

        current = self.head;    

        if(self.head == None):    

            print("List is empty");    

            return;    

        print("Nodes of doubly linked list: ");    

        while(current != None):     

            print(current.data),;    

            current = current.next;                   

dList = DoublyLinkedList();    

dList.addNode(1);    

dList.addNode(2);    

dList.addNode(3);    

dList.addNode(4);    

dList.addNode(5);    

dList.display();  

Generate Captcha Using Python


from captcha.image import ImageCaptcha

image = ImageCaptcha(width = 280, height = 90)

captcha_text = 'python'

data = image.generate(captcha_text)

image.write(captcha_text,'CAPTCHA.png')


Program to find minimum cost path

R = 3

C = 3

def minCost(cost, m, n):

tc = [[0 for x in range(C)] for x in range(R)]


tc[0][0] = cost[0][0]

for i in range(1, m + 1):

tc[i][0] = tc[i-1][0] + cost[i][0]

for j in range(1, n + 1):

tc[0][j] = tc[0][j-1] + cost[0][j]

for i in range(1, m + 1):

for j in range(1, n + 1):

tc[i][j] = min(tc[i-1][j-1], tc[i-1][j],tc[i][j-1]) + cost[i][j]

return tc[m][n]

cost = [[1, 2, 3],

[4, 8, 2],

[1, 5, 3]]

print(minCost(cost, 2, 2))


Convert nested tuple to custom key dictionary

sample_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))

print("The original tuple : " + str(sample_tuple))

res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in sample_tuple]

print("The converted dictionary : " + str(res))


Permutation of a given string using inbuilt function

from itertools import permutations

def allPermutations(str):

permList = permutations(str)

for perm in list(permList):

print (''.join(perm))

if __name__ == "__main__":

str = 'ABC'

allPermutations(str)


Validate an IP address using ReGex

import re

def Validate_It(IP):

regex = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|"\

"2[0-4][0-9]|25[0-5])\\.){3}"\

"([0-9]|[1-9][0-9]|1[0-9][0-9]|"\

"2[0-4][0-9]|25[0-5])"

regex1 = "((([0-9a-fA-F]){1,4})\\:){7}"\

"([0-9a-fA-F]){1,4}"

p = re.compile(regex)

p1 = re.compile(regex1)

if (re.search(p, IP)):

return "Valid IPv4"

elif (re.search(p1, IP)):

return "Valid IPv6"

return "Invalid IP"

IP = "203.120.223.13"

print(Validate_It(IP))

IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001"

print(Validate_It(IP))

IP = "2F33:12a0:3Ea0:0302"

print(Validate_It(IP))


Creating map using python

import folium

my_map4 = folium.Map(location = [28.5011226,77.4099794],zoom_start =12)

folium.Marker([28.704059, 77.102490],popup = 'Delhi').add_to(my_map4)

folium.Marker([28.5011226, 77.4099794],popup = 'Python For Engineers').add_to(my_map4)

folium.PolyLine(locations = [(28.704059, 77.102490), (28.5011226, 77.4099794)],line_opacity =0.5).add_to(my_map4)

my_map4.save("my_map4.html")

my_map4

Program for Cocktail Sort

def cocktailSort(a):

n = len(a)

swapped = True

start = 0

end = n-1

while (swapped==True):

swapped = False

for i in range (start, end):

if (a[i] > a[i+1]) :

a[i], a[i+1]= a[i+1], a[i]

swapped=True

if (swapped==False):

break

swapped = False

end = end-1

for i in range(end-1, start-1,-1):

if (a[i] > a[i+1]):

a[i], a[i+1] = a[i+1], a[i]

swapped = True

start = start+1

a = [5, 1, 4, 2, 8, 0, 2 ,6,7]

cocktailSort(a)

print("Sorted array is:")

for i in range(len(a)):

print ("%d" %a[i]),


Program for Gnome Sort

def gnomeSort( arr, n):

index = 0

while index < n:

if index == 0:

index = index + 1

if arr[index] >= arr[index - 1]:

index = index + 1

else:

arr[index], arr[index-1] = arr[index-1], arr[index]

index = index - 1

return arr

arr = [ 34, 2, 10, -9]

n = len(arr)

arr = gnomeSort(arr, n)

print ("Sorted seqquence after applying Gnome Sort :")

for i in arr:

print (i)

Program to find the maximum and minimum value node from a circular linked list

class Node:    

    def __init__(self,data):    

        self.data = data;    

        self.next = None;    

class CreateList:    

    def __init__(self):    

        self.head = Node(None);    

        self.tail = Node(None);    

        self.head.next = self.tail;    

        self.tail.next = self.head;      

    def add(self,data):    

        newNode = Node(data);    

        if self.head.data is None:    

            self.head = newNode;    

            self.tail = newNode;    

            newNode.next = self.head;    

        else:    

            self.tail.next = newNode;    

            self.tail = newNode;    

            self.tail.next = self.head;                 

    def minNode(self):    

        current = self.head;    

        minimum = self.head.data;    

        if(self.head == None):    

            print("List is empty");    

        else:    

            while(True):       

                if(minimum > current.data):    

                    minimum = current.data;    

                current= current.next;    

                if(current == self.head):    

                    break;    

        print("Minimum value node in the list: "+ str(minimum));    

    def maxNode(self):    

        current = self.head;    

        maximum = self.head.data;    

        if(self.head == None):    

            print("List is empty");    

        else:    

            while(True):       

                if(maximum < current.data):    

                    maximum = current.data;    

                current= current.next;    

                if(current == self.head):    

                    break;    

        print("Maximum value node in the list: "+ str(maximum));    

class CircularLinkedList:    

    cl = CreateList();    

    cl.add(5);    

    cl.add(20);    

    cl.add(10);    

    cl.add(1);    

    cl.minNode();    

    cl.maxNode();    


Vertical concatenation in matrix using loop

sample_list = [["Hi", "python"], ["welcome", "for"], ["to","engineers"]]

print("The original list : " + str(sample_list))

res = []

N = 0

while N != len(sample_list):

temp = ''

for idx in sample_list:

try: temp = temp + idx[N]

except IndexError: pass

res.append(temp)

N = N + 1

res = [ele for ele in res if ele]

print("List after column Concatenation : " + str(res))


Find number of times every day occurs in a Year

import datetime

import calendar

def day_occur_time(year):

days = [ "Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday",

"Sunday" ]

L = [52 for i in range(7)]

pos = -1

day = datetime.datetime(year, month = 1, day = 1).strftime("%A")

for i in range(7):

if day == days[i]:

pos = i

if calendar.isleap(year):

L[pos] += 1

L[(pos+1)%7] += 1

else:

L[pos] += 1

for i in range(7):

print(days[i], L[i])

year = 2020

day_occur_time(year)


Program to count uppercase, lowercase, special character and numeric values using Regex

import re

string = "Pythonforengineers !,* 12345"

uppercase_characters = re.findall(r"[A-Z]", string)

lowercase_characters = re.findall(r"[a-z]", string)

numerical_characters = re.findall(r"[0-9]", string)

special_characters = re.findall(r"[, .!?*]", string)

print("The no. of uppercase characters is", len(uppercase_characters))

print("The no. of lowercase characters is", len(lowercase_characters))

print("The no. of numerical characters is", len(numerical_characters))

print("The no. of special characters is", len(special_characters))


Program to find LCM

def calculate_lcm(x, y):  

    if x > y:  

        greater = x  

    else:  

        greater = y  

    while(True):  

        if((greater % x == 0) and (greater % y == 0)):  

            lcm = greater  

            break  

        greater += 1  

    return lcm    

num1 = int(input("Enter first number: "))  

num2 = int(input("Enter second number: "))  

print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2))  


Program to find Smallest K digit number divisible by X

 def answer(X, K):

MIN = pow(10, K-1)

if(MIN%X == 0):

return (MIN)

else:

return ((MIN + X) - ((MIN + X) % X))

X = 83;

K = 5;

print(answer(X, K));


BMI Calculator Using Python

height = float(input("Enter height in foot"))

height_in_meter = height*12/39.37

weight = int(input("Enter weight in kg"))

BMI = weight/pow(height_in_meter,2)

print("BMI:-",BMI)

if BMI > 25:

print("Overweight")

elif BMI < 18:

print("Underweight")

else:

print("Fit")

Python script that takes the city name and returns the weather information of that city using web scraping

from bs4 import BeautifulSoup

import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

def weather(city):

    city=city.replace(" ","+")

    res = requests.get(f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers)

    print("Searching in google......\n")

    soup = BeautifulSoup(res.text,'html.parser')   

    location = soup.select('#wob_loc')[0].getText().strip()  

    time = soup.select('#wob_dts')[0].getText().strip()       

    info = soup.select('#wob_dc')[0].getText().strip() 

    weather = soup.select('#wob_tm')[0].getText().strip()

    print(location)

    print(time)

    print(info)

    print(weather+"°C") 

print("enter the city name")

city=input()

city=city+" weather"

weather(city)

Create Graph Using Python

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([1,8])

ypoints = np.array([3,10])

plt.plot(xpoints,ypoints)

plt.show()

Drawing Corona Virus Using Turtle

from turtle import *

color('green')

bgcolor('black')

speed(10)

hideturtle()

b = 0

while b < 200:

right( b)

forward(b * 3)

b = b + 1

Program to draw pie chart in python

import matplotlib.pyplot as plt

x=[30,30,20,20]

labeks=["Python","Java","C","C++"]

plt.pie(x,labels=labeks)

plt.show()


PROGRAM TO CREATE INSTAGRAM LOGO IN PYTHON TURTLE

from turtle import  *

speed(5)

def om(x,y):

    penup()

    goto(x,y)

    pendown()

def om1(x,y,f,c,c1,c2):

    color(c)

    om(x,y)

    begin_fill()

    for i in range(4):

        forward(f)

        circle(c1,c2)

    end_fill()

def om2(c,x,y,c1):

    color(c)

    begin_fill()

    om(x, y)

    circle(c1)

    end_fill()


om1(-150,-120,350,"black",20,90)

om1(-110,-70,260,"white",20,90)

om1(-90,-50,220,"black",20,90)

om2("white",20,10,70)

om2("black",20,30,50)

om2("white",110,160,15)


color("black")

om(-120,-180)

write("INSTAGRAM",font=("Helvetica",40,"bold"))

hideturtle()

done()

Plotting Star Using Turtle

import turtle

s = turtle.Turtle()

s.right(75)

s.forward(100)

for i in range(4):

s.right(144)

s.forward(100)

turtle.done()


program to sort a list of tuples by second Item

def Sort_Tuple(tup):

lst = len(tup)

for i in range(0, lst):

for j in range(0, lst-i-1):

if (tup[j][1] > tup[j + 1][1]):

temp = tup[j]

tup[j]= tup[j + 1]

tup[j + 1]= temp

return tup

tup =[('for', 24), ('for', 10), ('programming', 28),

('python', 5), ('solution', 20), ('engineers', 15)]

print(Sort_Tuple(tup))


Colorful Spiral Web Using Turtle Graphics in Python

import turtle

colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange']

s= turtle.Pen()

s.speed(10)

turtle.bgcolor("black")

for x in range(200):

s.pencolor(colors[x%6]) 

s.width(x/100 + 1) 

s.forward(x) 

s.left(59) 

turtle.done()

s.speed(20)

turtle.bgcolor("black") 

for x in range(200):

s.pencolor(colors[x%6]) 

s.width(x/100 + 1) 

s.forward(x) 

s.left(59) 

turtle.done()


Remove all duplicates words from a given sentence

from collections import Counter

def remov_duplicates(input):

input = input.split(" ")

for i in range(0, len(input)):

input[i] = "".join(input[i])

Uniq = Counter(input)

s = " ".join(Uniq.keys())

print (s)

if __name__ == "__main__":

input = 'Python is great and Java is also great'

remov_duplicates(input)


Program to Create a Lap Timer

import time

starttime=time.time()

lasttime=starttime

lapnum=1

print("Press ENTER to count laps.\nPress CTRL+C to stop")

try:

while True:

input()

laptime=round((time.time() - lasttime), 2)

totaltime=round((time.time() - starttime), 2)

print("Lap No. "+str(lapnum))

print("Total Time: "+str(totaltime))

print("Lap Time: "+str(laptime))

print("*"*10)

lasttime=time.time()

lapnum+=1

except KeyboardInterrupt:

print("Done")


Program to find yesterday’s, today’s and tomorrow’s date

from datetime import datetime, timedelta

currentday = datetime.now()

yesterday = currentday - timedelta(1)

tomorrow = currentday + timedelta(1)

print("Yesterday = ", yesterday.strftime('%d-%m-%Y'))

print("Today = ", currentday.strftime('%d-%m-%Y'))

print("Tomorrow = ", tomorrow.strftime('%d-%m-%Y'))


Program to Print Matrix in Z form

arr = [[5, 6, 7, 8],

    [1, 2, 3, 4],

    [5, 6, 7, 8],

    [9, 8, 7, 5]]

a = len(arr[0])

i=0

for j in range(0, a-1):

print(arr[i][j], end =" ")

k = 1

for i in range(0, a):

for j in range(a, 0, -1):

if(j==a-k):

print(arr[i][j], end = " ")

break;

k+=1

i=a-1;

for j in range(0, a):

print(arr[i][j], end = " ")

gTTS (Google Text-to-Speech)

 gTTS (Google Text-to-Speech)

a Python library and CLI tool to interface with Google Translate text-to-speech API

Features

Customizable speech-specific sentence tokenizer that allows for unlimited lengths of text to be read, all while keeping proper intonation, abbreviations, decimals and more

Customizable text pre-processors which can, for example, provide pronunciation corrections

Installation   $ pip install gTTS

Example  $ gtts-cli 'hello' --output hello.mp3

More

Convert Text to Speech

from gtts import gTTS

import os

mytext = 'Welcome to Python for Engineers,A Complete solution for python programming'

language = 'en'

myobj = gTTS(text=mytext, lang=language, slow=False)

myobj.save('WelcomeMsg.mp3')


Word Guessing Game

import random

words = ['rainbow', 'computer', 'science', 'programming',

'python', 'mathematics', 'game', 'condition',

'reverse', 'return', 'board']


word = random.choice(words)

print("Guess the characters")

guesses = ' '

turns = 11

while turns > 0:

failed = 0

for char in word:


if char in guesses:

print(char)

else:

print("_")

failed += 1

if failed == 0:

print("You Win")

print("The word is: ", word)

break

guess = input("guess a character:")

guesses += guess


if guess not in word:

turns -= 1

print("Wrong")

print("You have", + turns, 'more guesses')

if turns == 0:

print("You Loose")

Test Internet Speed using Python program

import speedtest  

st = speedtest.Speedtest()

option = int(input('''What speed do you want to test in Megabits:  

1) Download Speed  

2) Upload Speed  

Your Choice: '''))

if option == 1:   

    print(st.download())    

elif option == 2:   

    print(st.upload())  

else:  

    print("Please enter the correct choice !")

Broadcasting in NumPy


 #Broadcasting
import numpy as np
# We will add,multiply, subtract  the vector v to each row of the matrix x,
x = np.array([[1,2,3], [4,5,6], [7,8,9]])
v = np.array([1, 0, 1])
print(x)
print(v)                 
y = x + v
y1= x * v
y2= x - v
print("Addition\n",y,"\n","Multiplication \n",y1,"\n","Subtraction \n",y2) 

Drawing a H-Tree Fractal using turtle in python program


import turtle
SPEED = 8
BG_COLOR = "red"
PEN_COLOR = "lightgreen"
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
DRAWING_WIDTH = 500
DRAWING_HEIGHT = 500
PEN_WIDTH = 5
TITLE = "H-Tree Fractal"
FRACTAL_DEPTH = 3
def draw_line(tur, pos1, pos2):
    tur.penup()
    tur.goto(pos1[0], pos1[1])
    tur.pendown()
    tur.goto(pos2[0], pos2[1])

def recursive_draw(tur, x, y, width, height, count):
    draw_line(
        tur,
        [x + width * 0.25, height // 2 + y],
        [x + width * 0.75, height // 2 + y],
    )
    draw_line(
        tur,
        [x + width * 0.25, (height * 0.5) // 2 + y],
        [x + width * 0.25, (height * 1.5) // 2 + y],
    )
    draw_line(
        tur,
        [x + width * 0.75, (height * 0.5) // 2 + y],
        [x + width * 0.75, (height * 1.5) // 2 + y],
    )
    if count <= 0: 
        return
    else: 
        count -= 1
    
        recursive_draw(tur, x, y, width // 2, height // 2, count)
        recursive_draw(tur, x + width // 2, y, width // 2, height // 2, count)
       recursive_draw(tur, x, y + width // 2, width // 2, height // 2, count)
       recursive_draw(tur, x + width // 2, y + width // 2, width // 2, height // 2, count)

if __name__ == "__main__":
    # Screen setup
    screen = turtle.Screen()
    screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
    screen.title(TITLE)
    screen.bgcolor(BG_COLOR)
    # Turtle artist (pen) setup
    artist = turtle.Turtle()
    artist.hideturtle()
    artist.pensize(PEN_WIDTH)
    artist.color(PEN_COLOR)
    artist.speed(SPEED)
   
    recursive_draw(artist, - DRAWING_WIDTH / 2, - DRAWING_HEIGHT / 2, DRAWING_WIDTH, DRAWING_HEIGHT, FRACTAL_DEPTH)
   
    turtle.done()

Drawing a fractal tree using turtle in python program


 import turtle
MINIMUM_BRANCH_LENGTH = 15
def build_tree(t, branch_length, shorten_by, angle):
  if branch_length > MINIMUM_BRANCH_LENGTH:
    t.forward(branch_length)
    new_length = branch_length - shorten_by
    t.left(angle)
    build_tree(t, new_length, shorten_by, angle)
    t.right(angle * 2)
    build_tree(t, new_length, shorten_by, angle)
    t.left(angle)
    t.backward(branch_length)
tree = turtle.Turtle()
tree.hideturtle()
tree.setheading(90)
tree.color('red')
build_tree(tree, 50, 5, 30)
turtle.mainloop()

Biopython - Python Tools for Computational Molecular Biology


Biopython is a set of freely available tools for biological computation written in Python by an international team of developers.

HUGO - The world’s fastest framework for building websites

Hugo is one of the most popular open-source static site generators. With its amazing speed and flexibility, Hugo makes building websites fun again.

Hugo Features

Hugo boasts blistering speed, robust content management, and a powerful templating language making it a great fit for all kinds of static websites.

General 

Extremely fast build times (< 1 ms per page)

Completely cross platform, with easy installation on macOS, Linux, Windows, and more

Renders changes on the fly with LiveReload as you develop

Powerful theming

Host your site anywhere

Organization 

Straightforward organization for your projects, including website sections

Customizable URLs

Support for configurable taxonomies, including categories and tags

Sort content as you desire through powerful template functions

Automatic table of contents generation

Dynamic menu creation

Pretty URLs support

Permalink pattern support

Redirects via aliases

Content 

Native Markdown and Emacs Org-Mode support, as well as other languages via external helpers (see supported formats)

TOML, YAML, and JSON metadata support in front matter

Customizable homepage

Multiple content types

Automatic and user defined content summaries

Shortcodes to enable rich content inside of Markdown

“Minutes to Read” functionality

“WordCount” functionality

Additional Features 

Integrated Disqus comment support

Integrated Google Analytics support

Automatic RSS creation

Support for Go HTML templates

Syntax highlighting powered by Chroma

Python Arithmetic Operators - An Review

I was well versed in python programming.

One morning a question was shooted at me by one of the blog followers

What is the output of   6/2 , 6//2 , 6%2

I was able to provide the answer for 6%2 as zero, but confused to answer 6/2 and 6//2 

/ Division              # Provide floating point as output 

// Floor division      #Rounds the result down to the nearest whole number

% Modulus              # Remainder 

Python named TIOBE’s programming language of 2020




Python has won the TIOBE programming language of the year award! This is for the fourth time in the history, which is a record! The title is awarded to the programming language that has gained most popularity in one year. Python made a positive jump of 2.01% in 2020. Programming language C++ is a very close runner up with an increase of 1.99%. Other winners are C (+1.66%), Groovy (+1.23%) and R (+1.10%).

More Details


Python Programming for Blood Bank Management System

import MySQLdb
from Tkinter import *
from PIL import Image
db=MySQLdb.connect("localhost","root","pswd","bbms")
cursor=db.cursor()
root = Tk()
image1=PhotoImage(file="/home/aishwarya/Downloads/bg.gif")
panel=Label(root,image=image1,bg="black").place(x=0,y=0,relwidth=1,relheight=1)
root.title("BLOOD BANK")
root.geometry("1920x1080")
root.configure(background='white')
l3=Label(root,text="BLOOD BANK SYSTEM",bg='white',font = "Helvetica 15 bold").place(x=450,y=40,w=300,h=40)
l1=Label(root,text="Click to enter the details of the donor",bg='white',font="Helvetica 12").place(x=80,y=100,w=300,h=40)
b1=Button(root,text="Donor Details",command=lambda : donordetails()).place(x=80,y=150)
l2=Label(root,text="Click to enter the details of the blood",bg='white',font="Helvetica 12").place(x=80,y=200,w=300,h=40)
b2=Button(root,text="Blood Details",command=lambda : blooddetails()).place(x=80,y=250)
l3=Label(root,text="Click to make a request for blood",bg='white',font="Helvetica 12").place(x=80,y=300,w=300,h=40)
b3=Button(root,text="Blood Request",command=lambda : requestblood()).place(x=80,y=350)
b2=Button(root,text="Exit",command=lambda : stop(root)).place(x=80,y=400)
v = StringVar()
def insertDonor(name,age,gender,address,contactno):
insert = "INSERT INTO donors(name,age,gender,address,contactno) VALUES('"+name+"','"+age+"','"+gender+"','"+address+"',"+"'"+contactno+"')"
try:
cursor.execute(insert)
db.commit()
except:
db.rollback()
def insertBlood(bloodgroup,platelet,rbc):
insert= "INSERT INTO blood(bloodgroup,platelet,rbc,date) VALUES('"+bloodgroup+"',"+"'"+platelet+"',"+"'"+rbc+"',"+"CURDATE())"
try:
cursor.execute(insert)
db.commit()
except:
db.rollback()
def retrieve(bg):
request="select * from donors inner join blood using(id) where bloodgroup='"+bg+"'"
try:
cursor.execute(request)
rows=cursor.fetchall()
db.commit()
print (len(rows))
return rows
except:
db.rollback() 
def sel():
   selection = "You selected the option " + v.get()
   print (selection)
def donordetails():
#global v
root=Toplevel()
root.title("BLOOD BANK")
root.geometry("1024x768")
root.configure(background ='#FF8F8F')
l1=Label(root,text="Name:",bg='white',font="Helvetica 12").place(x=40,y=40)
l2=Label(root,text="Age:",bg='white',font="Helvetica 12").place(x=40,y=80)
l3=Label(root,text="Gender:",bg='white',font="Helvetica 12").place(x=40,y=120)
l4=Label(root,text="Address:",bg='white',font="Helvetica 12").place(x=40,y=220)
l5=Label(root,text="Contact:",bg='white',font="Helvetica 12").place(x=40,y=260)
e1=Entry(root)
e1.place(x=120,y=40)
e2=Entry(root)
e2.place(x=120,y=80)
r1=Radiobutton(root,text="Male",variable=v,value="Male",command=sel).place(x=120,y=120)
r2=Radiobutton(root,text="Female",variable=v,value="Female",command=sel).place(x=120,y=150)
r3=Radiobutton(root,text="Other",variable=v,value="Other",command=sel).place(x=120,y=180)
e4=Entry(root)
e4.place(x=120,y=220)
e5=Entry(root)
e5.place(x=120,y=260)
root.mainloop()
def blooddetails():
root=Tk()
root.title("BLOOD BANK")
root.geometry("1024x768")
root.configure(background ='#FF8F8F')
l1=Label(root,text="Blood Group:",font="Helvetica 12").place(x=40,y=40,w=250,h=20)
l2=Label(root,text="PLatetelet count (in 100 thousands):",font="Helvetica 12").place(x=40,y=80,w=250,h=20)
l3=Label(root,text="RBC count (in millions):",font="Helvetica 12").place(x=40,y=120,w=250,h=20)
e1=Entry(root)
e1.place(x=350,y=40)
e2=Entry(root)
e2.place(x=350,y=80)
e3=Entry(root)
e3.place(x=350,y=120)
b2=Button(root,text="Back",command=lambda : stop(root)).place(x=200,y=160)
b1=Button(root,text="Submit",command=lambda : insertBlood(e1.get(),e2.get(),e3.get())).place(x=40,y=160)
root.mainloop()
def grid1(bg):
root=Tk()
root.title("LIST OF MATCHING DONORS")
root.geometry("750x500")
root.configure(background='#0C43F0')
rows=retrieve(bg)
x=0
for row in rows:
l1=Label(root,text=row[0],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=0,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l2=Label(root,text=row[1],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=1,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l3=Label(root,text=row[2],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=2,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l4=Label(root,text=row[3],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=3,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l5=Label(root,text=row[4],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=4,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l6=Label(root,text=row[5],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=5,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l7=Label(root,text=row[6],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=6,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l8=Label(root,text=row[7],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=7,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l9=Label(root,text=row[8],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=8,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
l10=Label(root,text=row[9],bg="#1EDEF2",font = "Verdana 15 bold").grid(row=x,column=9,sticky='E',padx=5,pady=5,ipadx=5,ipady=5)
x=x+1
root.mainloop()
def requestblood():
root=Tk()
root.title("BLOOD BANK")
root.geometry("1024x720")
root.configure(background='#FF8F8F')
l=Label(root,text="Enter the blood group").place(x=50,y=50,w=400,h=40)
e=Entry(root)
e.place(x=500,y=50)
b2=Button(root,text="Back",command=lambda : stop(root)).place(x=600,y=100)
b=Button(root,text="ENTER",command=lambda : grid1(e.get())).place(x=500,y=100)
root.mainloop()
def stop(root):
root.destroy()
root.mainloop()