Master Python with examples, opportunities, and hands-on coding!
Python is one of the most popular programming languages in the world. It is versatile, beginner-friendly, and widely used in web development, data analysis, machine learning, artificial intelligence, and more. Learning Python can open doors to countless opportunities and exciting projects.
# Example 1: Hello World Program
print("Hello, World!")
# Example 2: Simple Calculator
def add(a, b):
return a + b
print("Sum:", add(5, 3))
# Example 3: Age Calculator
from datetime import date
birth_year = int(input("Enter your birth year: "))
current_year = date.today().year
age = current_year - birth_year
print("Your age is:", age)
# Example 4: Temperature Converter
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}C is {fahrenheit}F")
# Example 3: Alarm clock
# Import Required Library
from tkinter import *
import datetime
import time
import winsound
from threading import *
# Create Object
root = Tk()
# Set geometry
root.geometry("400x200")
# Use Threading
def Threading():
t1=Thread(target=alarm)
t1.start()
def alarm():
# Infinite Loop
while True:
# Set Alarm
set_alarm_time = f"{hour.get()}:{minute.get()}:{second.get()}"
# Wait for one seconds
time.sleep(1)
# Get current time
current_time = datetime.datetime.now().strftime("%H:%M:%S")
print(current_time,set_alarm_time)
# Check whether set alarm is equal to current time or not
if current_time == set_alarm_time:
print("Time to Wake up")
# Playing sound
winsound.PlaySound("sound.wav",winsound.SND_ASYNC)
# Add Labels, Frame, Button, Optionmenus
Label(root,text="Alarm Clock",font=("Helvetica 20 bold"),fg="red").pack(pady=10)
Label(root,text="Set Time",font=("Helvetica 15 bold")).pack()
frame = Frame(root)
frame.pack()
hour = StringVar(root)
hours = ('00', '01', '02', '03', '04', '05', '06', '07',
'08', '09', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23', '24'
)
hour.set(hours[0])
hrs = OptionMenu(frame, hour, *hours)
hrs.pack(side=LEFT)
minute = StringVar(root)
minutes = ('00', '01', '02', '03', '04', '05', '06', '07',
'08', '09', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23',
'24', '25', '26', '27', '28', '29', '30', '31',
'32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47',
'48', '49', '50', '51', '52', '53', '54', '55',
'56', '57', '58', '59', '60')
minute.set(minutes[0])
mins = OptionMenu(frame, minute, *minutes)
mins.pack(side=LEFT)
second = StringVar(root)
seconds = ('00', '01', '02', '03', '04', '05', '06', '07',
'08', '09', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23',
'24', '25', '26', '27', '28', '29', '30', '31',
'32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47',
'48', '49', '50', '51', '52', '53', '54', '55',
'56', '57', '58', '59', '60')
second.set(seconds[0])
secs = OptionMenu(frame, second, *seconds)
secs.pack(side=LEFT)
Button(root,text="Set Alarm",font=("Helvetica 15"),command=Threading).pack(pady=20)
# Execute Tkinter
root.mainloop()
# Example 5. get_links.
import requests as rq
from bs4 import BeautifulSoup
url = input("Enter Link: ")
if ("https" or "http") in url:
data = rq.get(url)
else:
data = rq.get("https://" + url)
soup = BeautifulSoup(data.text, "html.parser")
links = []
for link in soup.find_all("a"):
links.append(link.get("href"))
# Writing the output to a file (myLinks.txt) instead of to stdout
# You can change 'a' to 'w' to overwrite the file each time
with open("myLinks.txt", 'a') as saved:
print(links[:10], file=saved)
beautifulsoup4==4.9.2
requests==2.24.0
# Example 6:AudioBook
#Importing Libraries
#Importing Google Text to Speech library
from gtts import gTTS
#Importing PDF reader PyPDF2
import PyPDF2
#Open file Path
pdf_File = open('name.pdf', 'rb')
#Create PDF Reader Object
pdf_Reader = PyPDF2.PdfFileReader(pdf_File)
count = pdf_Reader.numPages # counts number of pages in pdf
textList = []
#Extracting text data from each page of the pdf file
for i in range(count):
try:
page = pdf_Reader.getPage(i)
textList.append(page.extractText())
except:
pass
#Converting multiline text to single line text
textString = " ".join(textList)
print(textString)
#Set language to english (en)
language = 'en'
#Call GTTS
myAudio = gTTS(text=textString, lang=language, slow=False)
#Save as mp3 file
myAudio.save("Audio.mp3")
# Example 7: Baidu_POI_crawl
import os
import os.path as osp
from util import get_baidu_poi
import argparse
def run(args):
baidu_web_ak = args.ak
city_str = args.city
roi_key = args.poi
output = args.save
if not osp.exists(output):
os.makedirs(output)
get_baidu_poi(roi_key, city_str, baidu_web_ak, output)
print("current area completed")
parser = argparse.ArgumentParser(description="input parameters")
parser.add_argument("--ak", type=str, required=True, help="Baidu web ak")
parser.add_argument("--city", type=str, required=True, help="City name")
parser.add_argument("--poi", type=str, required=True, help="POI key")
parser.add_argument("--save", type=str, default="output", help="Save path")
if __name__ == "__main__":
args = parser.parse_args()
run(args)
util.py
import requests
import json
import time
# call API
def get_baidu_poi(roi_key, city_str, baidu_ak, output):
"""
inputs:
roi_key: poi name
city_str: city name
baidu_ak: baidu web API AK
output: file save path
"""
now_time = time.strftime("%Y-%m-%d")
page_num = 0
logfile = open(output + "/" + now_time + ".log", "a+", encoding="utf-8")
file = open(output + "/" + now_time + ".txt", "a+", encoding="utf-8")
while True:
try:
URL = "http://api.map.baidu.com/place/v2/search?query=" + roi_key + \
"®ion=" + city_str + \
"&output=json" + \
"&ak=" + baidu_ak + \
"&scope=2" + \
"&page_size=20" + \
"&page_num=" + str(page_num)
resp = requests.get(URL)
res = json.loads(resp.text)
if len(res["results"]) == 0:
logfile.writelines(time.strftime("%Y-%m-%d-%H-%M-%S") + " " + city_str + " " + str(page_num) + "\n")
break
else:
for r in res["results"]:
j_name = r["name"]
j_lat = r["location"]["lat"]
j_lon = r["location"]["lng"]
j_area = r["area"]
j_add = r["address"]
j_str = str(j_name) + "," + str(j_lon) + "," + str(j_lat) + "," + str(j_area) + "," + str(j_add) + "\n"
file.writelines(j_str)
page_num += 1
time.sleep(1)
except:
print("except")
logfile.writelines(time.strftime("%Y-%m-%d-%H-%M-%S") + " " + city_str + " " + str(page_num) + "\n")
break
# Example 8: biling_system
from tkinter import*
import random
import os
from tkinter import messagebox
# ============main============================
class Bill_App:
def __init__(self, root):
self.root = root
self.root.geometry("1350x700+0+0")
self.root.title("Billing Software")
bg_color = "#badc57"
title = Label(self.root, text="Billing Software", font=('times new roman', 30, 'bold'), pady=2, bd=12, bg="#badc57", fg="Black", relief=GROOVE)
title.pack(fill=X)
# ================variables=======================
self.sanitizer = IntVar()
self.mask = IntVar()
self.hand_gloves = IntVar()
self.dettol = IntVar()
self.newsprin = IntVar()
self.thermal_gun = IntVar()
# ============grocery==============================
self.rice = IntVar()
self.food_oil = IntVar()
self.wheat = IntVar()
self.daal = IntVar()
self.flour = IntVar()
self.maggi = IntVar()
#=============coldDtinks=============================
self.sprite = IntVar()
self.limka = IntVar()
self.mazza = IntVar()
self.coke = IntVar()
self.fanta = IntVar()
self.mountain_duo = IntVar()
# ==============Total product price================
self.medical_price = StringVar()
self.grocery_price = StringVar()
self.cold_drinks_price = StringVar()
# ==============Customer==========================
self.c_name = StringVar()
self.c_phone = StringVar()
self.bill_no = StringVar()
x = random.randint(1000, 9999)
self.bill_no.set(str(x))
self.search_bill = StringVar()
# ===============Tax================================
self.medical_tax = StringVar()
self.grocery_tax = StringVar()
self.cold_drinks_tax = StringVar()
# =============customer retail details======================
F1 = LabelFrame(self.root, text="Customer Details", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
F1.place(x=0, y=80, relwidth=1)
cname_lbl = Label(F1, text="Customer Name:", bg=bg_color, font=('times new roman', 15, 'bold'))
cname_lbl.grid(row=0, column=0, padx=20, pady=5)
cname_txt = Entry(F1, width=15, textvariable=self.c_name, font='arial 15', bd=7, relief=GROOVE)
cname_txt.grid(row=0, column=1, pady=5, padx=10)
cphn_lbl = Label(F1, text="Customer Phone:", bg="#badc57", font=('times new roman', 15, 'bold'))
cphn_lbl.grid(row=0, column=2, padx=20, pady=5)
cphn_txt = Entry(F1, width=15, textvariable=self.c_phone, font='arial 15', bd=7, relief=GROOVE)
cphn_txt.grid(row=0, column=3, pady=5, padx=10)
c_bill_lbl = Label(F1, text="Bill Number:", bg="#badc57", font=('times new roman', 15, 'bold'))
c_bill_lbl.grid(row=0, column=4, padx=20, pady=5)
c_bill_txt = Entry(F1, width=15, textvariable=self.search_bill, font='arial 15', bd=7, relief=GROOVE)
c_bill_txt.grid(row=0, column=5, pady=5, padx=10)
bil_btn = Button(F1, text="Search", command=self.find_bill, width=10, bd=7, font=('arial', 12, 'bold'), relief=GROOVE)
bil_btn.grid(row=0, column=6, pady=5, padx=10)
# ===================Medical====================================
F2 = LabelFrame(self.root, text="Medical Purpose", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
F2.place(x=5, y=180, width=325, height=380)
sanitizer_lbl = Label(F2, text="Sanitizer", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
sanitizer_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='W')
sanitizer_txt = Entry(F2, width=10, textvariable=self.sanitizer, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
sanitizer_txt.grid(row=0, column=1, padx=10, pady=10)
mask_lbl = Label(F2, text="Mask", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
mask_lbl.grid(row=1, column=0, padx=10, pady=10, sticky='W')
mask_txt = Entry(F2, width=10, textvariable=self.mask, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
mask_txt.grid(row=1, column=1, padx=10, pady=10)
hand_gloves_lbl = Label(F2, text="Hand Gloves", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
hand_gloves_lbl.grid(row=2, column=0, padx=10, pady=10, sticky='W')
hand_gloves_txt = Entry(F2, width=10, textvariable=self.hand_gloves, font=('times new roman', 16, 'bold'), bd=5, relief =GROOVE)
hand_gloves_txt.grid(row=2, column=1, padx=10, pady=10)
dettol_lbl = Label(F2, text="Dettol", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
dettol_lbl.grid(row=3, column=0, padx=10, pady=10, sticky='W')
dettol_txt = Entry(F2, width=10, textvariable=self.dettol, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
dettol_txt.grid(row=3, column=1, padx=10, pady=10)
newsprin_lbl = Label(F2, text="Newsprin", font =('times new roman', 16, 'bold'), bg = "#badc57", fg = "black")
newsprin_lbl.grid(row=4, column=0, padx=10, pady=10, sticky='W')
newsprin_txt = Entry(F2, width=10, textvariable=self.newsprin, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
newsprin_txt.grid(row=4, column=1, padx=10, pady=10)
thermal_gun_lbl = Label(F2, text="Thermal Gun", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
thermal_gun_lbl.grid(row=5, column=0, padx=10, pady=10, sticky='W')
thermal_gun_txt = Entry(F2, width=10, textvariable=self.thermal_gun, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
thermal_gun_txt.grid(row=5, column=1, padx=10, pady=10)
# ==========GroceryItems=========================
F3 = LabelFrame(self.root, text="Grocery Items", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
F3.place(x=340, y=180, width=325, height=380)
rice_lbl = Label(F3, text="Rice", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
rice_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='W')
rice_txt = Entry(F3, width=10, textvariable=self.rice, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
rice_txt.grid(row=0, column=1, padx=10, pady=10)
food_oil_lbl = Label(F3, text="Food Oil", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
food_oil_lbl.grid(row=1, column=0, padx=10, pady=10, sticky='W')
food_oil_txt = Entry(F3, width=10, textvariable=self.food_oil, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
food_oil_txt.grid(row=1, column=1, padx=10, pady=10)
wheat_lbl = Label(F3, text="Wheat", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
wheat_lbl.grid(row=2, column=0, padx=10, pady=10, sticky='W')
wheat_txt = Entry(F3, width=10, textvariable=self.wheat, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
wheat_txt.grid(row=2, column=1, padx=10, pady=10)
daal_lbl = Label(F3, text="Daal", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
daal_lbl.grid(row=3, column=0, padx=10, pady=10, sticky='W')
daal_txt = Entry(F3, width=10, textvariable=self.daal, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
daal_txt.grid(row=3, column=1, padx=10, pady=10)
flour_lbl = Label(F3, text="Flour", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
flour_lbl.grid(row=4, column=0, padx=10, pady=10, sticky='W')
flour_txt = Entry(F3, width=10, textvariable=self.flour, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
flour_txt.grid(row=4, column=1, padx=10, pady=10)
maggi_lbl = Label(F3, text="Maggi", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
maggi_lbl.grid(row=5, column=0, padx=10, pady=10, sticky='W')
maggi_txt = Entry(F3, width=10, textvariable=self.maggi, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
maggi_txt.grid(row=5, column=1, padx=10, pady=10)
# ===========ColdDrinks================================
F4 = LabelFrame(self.root, text="Cold Drinks", font=('times new roman', 15, 'bold'), bd=10, fg="Black", bg="#badc57")
F4.place(x=670, y=180, width=325, height=380)
sprite_lbl = Label(F4, text="Sprite", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
sprite_lbl.grid(row=0, column=0, padx=10, pady=10, sticky='W')
sprite_txt = Entry(F4, width=10, textvariable=self.sprite, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
sprite_txt.grid(row=0, column=1, padx=10, pady=10)
limka_lbl = Label(F4, text="Limka", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
limka_lbl.grid(row=1, column=0, padx=10, pady=10, sticky='W')
limka_txt = Entry(F4, width=10, textvariable=self.limka, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
limka_txt.grid(row=1, column=1, padx=10, pady=10)
mazza_lbl = Label(F4, text="Mazza", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
mazza_lbl.grid(row=2, column=0, padx=10, pady=10, sticky='W')
wheat_txt = Entry(F4, width=10, textvariable=self.mazza, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
wheat_txt.grid(row=2, column=1, padx=10, pady=10)
coke_lbl = Label(F4, text="Coke", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
coke_lbl.grid(row=3, column=0, padx=10, pady=10, sticky='W')
coke_txt = Entry(F4, width=10, textvariable=self.coke, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
coke_txt.grid(row=3, column=1, padx=10, pady=10)
fanta_lbl = Label(F4, text="Fanta", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
fanta_lbl.grid(row=4, column=0, padx=10, pady=10, sticky='W')
fanta_txt = Entry(F4, width=10, textvariable=self.fanta, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
fanta_txt.grid(row=4, column=1, padx=10, pady=10)
mountain_duo_lbl = Label(F4, text="Mountain Duo", font=('times new roman', 16, 'bold'), bg="#badc57", fg="black")
mountain_duo_lbl.grid(row=5, column=0, padx=10, pady=10, sticky='W')
mountain_duo_txt = Entry(F4, width=10, textvariable=self.mountain_duo, font=('times new roman', 16, 'bold'), bd=5, relief=GROOVE)
mountain_duo_txt.grid(row=5, column=1, padx=10, pady=10)
# =================BillArea======================
F5 = Frame(self.root, bd=10, relief=GROOVE)
F5.place(x=1010, y=180, width=350, height=380)
bill_title = Label(F5, text="Bill Area", font='arial 15 bold', bd=7, relief=GROOVE)
bill_title.pack(fill=X)
scroll_y = Scrollbar(F5, orient=VERTICAL)
self.txtarea = Text(F5, yscrollcommand=scroll_y.set)
scroll_y.pack(side=RIGHT, fill=Y)
scroll_y.config(command=self.txtarea.yview)
self.txtarea.pack(fill=BOTH, expand=1)
# =======================ButtonFrame=============
F6 = LabelFrame(self.root, text="Bill Area", font=('times new roman', 14, 'bold'), bd=10, fg="Black", bg="#badc57")
F6.place(x=0, y=560, relwidth=1, height=140)
m1_lbl = Label(F6, text="Total Medical Price", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
m1_lbl.grid(row=0, column=0, padx=20, pady=1, sticky='W')
m1_txt = Entry(F6, width=18, textvariable=self.medical_price, font='arial 10 bold', bd=7, relief=GROOVE)
m1_txt.grid(row=0, column=1, padx=18, pady=1)
m2_lbl = Label(F6, text="Total Grocery Price", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
m2_lbl.grid(row=1, column=0, padx=20, pady=1, sticky='W')
m2_txt = Entry(F6, width=18, textvariable=self.grocery_price, font='arial 10 bold', bd=7, relief=GROOVE)
m2_txt.grid(row=1, column=1, padx=18, pady=1)
m3_lbl = Label(F6, text="Total Cold Drinks Price", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
m3_lbl.grid(row=2, column=0, padx=20, pady=1, sticky='W')
m3_txt = Entry(F6, width=18, textvariable=self.cold_drinks_price, font='arial 10 bold', bd=7, relief=GROOVE)
m3_txt.grid(row=2, column=1, padx=18, pady=1)
m4_lbl = Label(F6, text="Medical Tax", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
m4_lbl.grid(row=0, column=2, padx=20, pady=1, sticky='W')
m4_txt = Entry(F6, width=18, textvariable=self.medical_tax, font='arial 10 bold', bd=7, relief=GROOVE)
m4_txt.grid(row=0, column=3, padx=18, pady=1)
m5_lbl = Label(F6, text="Grocery Tax", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
m5_lbl.grid(row=1, column=2, padx=20, pady=1, sticky='W')
m5_txt = Entry(F6, width=18, textvariable=self.grocery_tax, font='arial 10 bold', bd=7, relief=GROOVE)
m5_txt.grid(row=1, column=3, padx=18, pady=1)
m6_lbl = Label(F6, text="Cold Drinks Tax", font=('times new roman', 14, 'bold'), bg="#badc57", fg="black")
m6_lbl.grid(row=2, column=2, padx=20, pady=1, sticky='W')
m6_txt = Entry(F6, width=18, textvariable=self.cold_drinks_tax, font='arial 10 bold', bd=7, relief=GROOVE)
m6_txt.grid(row=2, column=3, padx=18, pady=1)
# =======Buttons-======================================
btn_f = Frame(F6, bd=7, relief=GROOVE)
btn_f.place(x=760, width=580, height=105)
total_btn = Button(btn_f, command=self.total, text="Total", bg="#535C68", bd=2, fg="white", pady=15, width=12, font='arial 13 bold')
total_btn.grid(row=0, column=0, padx=5, pady=5)
generateBill_btn = Button(btn_f, command=self.bill_area, text="Generate Bill", bd=2, bg="#535C68", fg="white", pady=12, width=12, font='arial 13 bold')
generateBill_btn.grid(row=0, column=1, padx=5, pady=5)
clear_btn = Button(btn_f, command=self.clear_data, text="Clear", bg="#535C68", bd=2, fg="white", pady=15, width=12, font='arial 13 bold')
clear_btn.grid(row=0, column=2, padx=5, pady=5)
exit_btn = Button(btn_f, command=self.exit_app, text="Exit", bd=2, bg="#535C68", fg="white", pady=15, width=12, font='arial 13 bold')
exit_btn.grid(row=0, column=3, padx=5, pady=5)
self.welcome_bill()
#================totalBill==========================
def total(self):
self.m_h_g_p = self.hand_gloves.get()*12
self.m_s_p = self.sanitizer.get()*2
self.m_m_p = self.mask.get()*5
self.m_d_p = self.dettol.get()*30
self.m_n_p = self.newsprin.get()*5
self.m_t_g_p = self.thermal_gun.get()*15
self.total_medical_price = float(self.m_m_p+self.m_h_g_p+self.m_d_p+self.m_n_p+self.m_t_g_p+self.m_s_p)
self.medical_price.set("Rs. "+str(self.total_medical_price))
self.c_tax = round((self.total_medical_price*0.05), 2)
self.medical_tax.set("Rs. "+str(self.c_tax))
self.g_r_p = self.rice.get()*10
self.g_f_o_p = self.food_oil.get()*10
self.g_w_p = self.wheat.get()*10
self.g_d_p = self.daal.get()*6
self.g_f_p = self.flour.get()*8
self.g_m_p = self.maggi.get()*5
self.total_grocery_price = float(self.g_r_p+self.g_f_o_p+self.g_w_p+self.g_d_p+self.g_f_p+self.g_m_p)
self.grocery_price.set("Rs. " + str(self.total_grocery_price))
self.g_tax = round((self.total_grocery_price*5), 2)
self.grocery_tax.set("Rs. " + str(self.g_tax))
self.c_d_s_p = self.sprite.get()*10
self.c_d_l_p = self.limka.get()*10
self.c_d_m_p = self.mazza.get()*10
self.c_d_c_p = self.coke.get()*10
self.c_d_f_p = self.fanta.get()*10
self.c_m_d = self.mountain_duo.get()*10
self.total_cold_drinks_price = float(self.c_d_s_p+self.c_d_l_p+self.c_d_m_p+self.c_d_c_p+self.c_d_f_p+self.c_m_d)
self.cold_drinks_price.set("Rs. "+str(self.total_cold_drinks_price))
self.c_d_tax = round((self.total_cold_drinks_price * 0.1), 2)
self.cold_drinks_tax.set("Rs. "+str(self.c_d_tax))
self.total_bill = float(self.total_medical_price+self.total_grocery_price+self.total_cold_drinks_price+self.c_tax+self.g_tax+self.c_d_tax)
#==============welcome-bill==============================
def welcome_bill(self):
self.txtarea.delete('1.0', END)
self.txtarea.insert(END, "\tWelcome Webcode Retail")
self.txtarea.insert(END, f"\n Bill Number:{self.bill_no.get()}")
self.txtarea.insert(END, f"\nCustomer Name:{self.c_name.get()}")
self.txtarea.insert(END, f"\nPhone Number{self.c_phone.get()}")
self.txtarea.insert(END, f"\n================================")
self.txtarea.insert(END, f"\nProducts\t\tQTY\t\tPrice")
#=========billArea=================================================
def bill_area(self):
if self.c_name.get() == " " or self.c_phone.get() == " ":
messagebox.showerror("Error", "Customer Details Are Must")
elif self.medical_price.get() == "Rs. 0.0" and self.grocery_price.get() == "Rs. 0.0" and self.cold_drinks_price.get()=="Rs. 0.0":
messagebox.showerror("Error", "No Product Purchased")
else:
self.welcome_bill()
# ============medical===========================
if self.sanitizer.get() != 0:
self.txtarea.insert(END, f"\n Sanitizer\t\t{self.sanitizer.get()}\t\t{self.m_s_p}")
if self.mask.get() != 0:
self.txtarea.insert(END, f"\n Sanitizer\t\t{self.mask.get()}\t\t{self.m_m_p}")
if self.hand_gloves.get() != 0:
self.txtarea.insert(END, f"\n Hand Gloves\t\t{self.hand_gloves.get()}\t\t{self.m_h_g_p}")
if self.dettol.get() != 0:
self.txtarea.insert(END, f"\n Dettol\t\t{self.dettol.get()}\t\t{self.m_d_p}")
if self.newsprin.get() != 0:
self.txtarea.insert(END, f"\n Newsprin\t\t{self.newsprin.get()}\t\t{self.m_n_p}")
if self.thermal_gun.get() != 0:
self.txtarea.insert(END , f"\n Thermal Gun\t\t{self.sanitizer.get()}\t\t{self.m_t_g_p}")
# ==============Grocery============================
if self.rice.get() != 0:
self.txtarea.insert(END, f"\n Rice\t\t{self.rice.get()}\t\t{self.g_r_p}")
if self.food_oil.get() != 0:
self.txtarea.insert(END, f"\n Food Oil\t\t{self.food_oil.get()}\t\t{self.g_f_o_p}")
if self.wheat.get() != 0:
self.txtarea.insert(END, f"\n Wheat\t\t{self.wheat.get()}\t\t{self.g_w_p}")
if self.daal.get() != 0:
self.txtarea.insert(END, f"\n Daal\t\t{self.daal.get()}\t\t{self.g_d_p}")
if self.flour.get() != 0:
self.txtarea.insert(END, f"\n Flour\t\t{self.flour.get()}\t\t{self.g_f_p}")
if self.maggi.get() != 0:
self.txtarea.insert(END, f"\n Maggi\t\t{self.maggi.get()}\t\t{self.g_m_p}")
#================ColdDrinks==========================
if self.sprite.get() != 0:
self.txtarea.insert(END, f"\n Sprite\t\t{self.sprite.get()}\t\t{self.c_d_s_p}")
if self.limka.get() != 0:
self.txtarea.insert(END, f"\n Sanitizer\t\t{self.limka.get()}\t\t{self.c_d_l_p}")
if self.mazza.get() != 0:
self.txtarea.insert(END, f"\n Mazza\t\t{self.mazza.get()}\t\t{self.c_d_m_p}")
if self.coke.get() != 0:
self.txtarea.insert(END, f"\n Dettol\t\t{self.coke.get()}\t\t{self.c_d_c_p}")
if self.fanta.get() != 0:
self.txtarea.insert(END, f"\n Fanta\t\t{self.newsprin.get()}\t\t{self.c_d_f_p}")
if self.mountain_duo.get() != 0:
self.txtarea.insert(END, f"\n Mountain Duo\t\t{self.sanitizer.get()}\t\t{self.c_m_d}")
self.txtarea.insert(END, f"\n--------------------------------")
# ===============taxes==============================
if self.medical_tax.get() != '0.0':
self.txtarea.insert(END, f"\n Medical Tax\t\t\t{self.medical_tax.get()}")
if self.grocery_tax.get() != '0.0':
self.txtarea.insert(END, f"\n Grocery Tax\t\t\t{self.grocery_tax.get()}")
if self.cold_drinks_tax.get() != '0.0':
self.txtarea.insert(END, f"\n Cold Drinks Tax\t\t\t{self.cold_drinks_tax.get()}")
self.txtarea.insert(END, f"\n Total Bil:\t\t\t Rs.{self.total_bill}")
self.txtarea.insert(END, f"\n--------------------------------")
self.save_bill()
#=========savebill============================
def save_bill(self):
op = messagebox.askyesno("Save Bill", "Do you want to save the bill?")
if op > 0:
self.bill_data = self.txtarea.get('1.0', END)
f1 = open("bills/"+str(self.bill_no.get())+".txt", "w")
f1.write(self.bill_data)
f1.close()
messagebox.showinfo("Saved", f"Bill no:{self.bill_no.get()} Saved Successfully")
else:
return
# ===================find_bill================================
def find_bill(self):
present = "no"
for i in os.listdir("bills/"):
if i.split('.')[0] == self.search_bill.get():
f1 = open(f"bills/{i}", "r")
self.txtarea.delete("1.0", END)
for d in f1:
self.txtarea.insert(END, d)
f1.close()
present = "yes"
if present == "no":
messagebox.showerror("Error", "Invalid Bill No")
# ======================clear-bill======================
def clear_data(self):
op = messagebox.askyesno("Clear", "Do you really want to Clear?")
if op > 0:
self.sanitizer.set(0)
self.mask.set(0)
self.hand_gloves.set(0)
self.dettol.set(0)
self.newsprin.set(0)
self.thermal_gun.set(0)
# ============grocery==============================
self.rice.set(0)
self.food_oil.set(0)
self.wheat.set(0)
self.daal.set(0)
self.flour.set(0)
self.maggi.set(0)
# =============coldDrinks=============================
self.sprite.set(0)
self.limka.set(0)
self.mazza.set(0)
self.coke.set(0)
self.fanta.set(0)
self.mountain_duo.set(0)
# ====================taxes================================
self.medical_price.set("")
self.grocery_price.set("")
self.cold_drinks_price.set("")
self.medical_tax.set("")
self.grocery_tax.set("")
self.cold_drinks_tax.set("")
self.c_name.set("")
self.c_phone.set("")
self.bill_no.set("")
x = random.randint(1000, 9999)
self.bill_no.set(str(x))
self.search_bill.set("")
self.welcome_bill()
# ===========exit=======================
def exit_app(self):
op = messagebox.askyesno("Exit", "Do you really want to exit?")
if op > 0:
self.root.destroy()
root = Tk()
obj = Bill_App(root)
root.mainloop()
# Example 9: Python_auto_draw
import pyautogui
import time
# time to change tabs from editor to paint;
time.sleep(10)
# it will remain clicked till program ends;
pyautogui.click()
# can be varied according to convininence
distance = 250
while distance > 0:
# right
pyautogui.dragRel(distance, 0, duration = 0.1)
distance -= 5
# down
pyautogui.dragRel(0, distance, duration = 0.1)
# left
pyautogui.dragRel(-distance, 0, duration = 0.1)
distance -= 5
#up
pyautogui.dragRel(0, -distance, duration = 0.1)
# Example 10: generate_qrcode
import qrcode
input_URL = "https://www.google.com/"
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=15,
border=4,
)
qr.add_data(input_URL)
qr.make(fit=True)
img = qr.make_image(fill_color="red", back_color="white")
img.save("url_qrcode.png")
print(qr.data_list)
# Example 11: EasyVideoPlayer
import cv2
import os
from pathlib import Path
from ffpyplayer.player import MediaPlayer
# User input for the name of the image file.
video_name = input("Name of the video file that you want to play: ")
# User input for the path of the image file.
video_directory_guess = input("Directory that may contain the video: ")
# This function finds your file. If you don't know the directory just type '/'
def find_the_video(file_name, directory_name):
files_found = []
for path, subdirs, files in os.walk(directory_name):
for name in files:
if(file_name == name):
file_path = os.path.join(path, name)
files_found.append(file_path)
print(files_found)
return files_found[0] # Return the path.
# Initialize the path of the image file.
video_directory = Path(find_the_video(video_name, video_directory_guess))
# Initialize the parent directory of the image path.
new_working_directory = video_directory.parent
# Change the working directory of the script.
os.chdir(new_working_directory)
video_path = find_the_video(video_name, video_directory_guess)
def PlayVideo(video_path):
video = cv2.VideoCapture(video_path)
player = MediaPlayer(video_path)
while True:
grabbed, frame = video.read()
audio_frame, val = player.get_frame()
if not grabbed:
print("End of video")
break
if cv2.waitKey(28) & 0xFF == ord("q"):
break
cv2.imshow("Video", frame)
if val != 'eof' and audio_frame is not None:
img, t = audio_frame
video.release()
cv2.destroyAllWindows()
PlayVideo(video_path)
requirements.txt
opencv-python==4.4.0.42
pathlib==1.0.1
ffpyplayer==4.3.1
# Example 3: Age Calculator
# Example 12: speech_to_text
import speech_recognition
def record_voice():
microphone = speech_recognition.Recognizer()
with speech_recognition.Microphone() as live_phone:
microphone.adjust_for_ambient_noise(live_phone)
print("I'm trying to hear you: ")
audio = microphone.listen(live_phone)
try:
phrase = microphone.recognize_google(audio, language='en')
return phrase
except speech_recognition.UnkownValueError:
return "I didn't understand what you said"
if __name__ == '__main__':
phrase = record_voice()
with open('you_said_this.txt','w') as file:
file.write(phrase)
print('the last sentence you spoke was saved in you_said_this.txt')
Click the button below to start your Python programming journey with more examples and projects!
Start Learning