Python Programming Examples
https://www.facebook.com/groups/791696432107081
Speedometer Program
# Program - Python - Speedometer
# www.bgmax.com.br/treinamentos
# Need to install the plotly library
# pip install plotly
# Import the required Plotly library to create interactive charts
import plotly.graph_objects as graf
# Create a figure object (figure) containing a speedometer with colors
figure = graf.Figure(graf.Indicator(
mode="gauge number delta", # Gauge mode (gauge = speedometer, number = number, delta = difference)
value=420, # Current indicator value (speed)
domain={'x': [0, 1], 'y': [0, 1]}, # Graph domain (position and size)
title={'text': "Speed", 'font': {'size': 24}}, # Indicator title
delta={'reference': 400, 'increasing': {'color': "mediumseagreen"}}, # Delta settings (difference)
gauge={
'axis': {'range': [0, 500], 'tickwidth': 1, 'tickcolor': "darkblue", 'tickvals': [0, 100, 200, 300, 400, 500]},
# Speedometer axis settings (range, thickness and colors)
'bar': {'color': "darkblue"}, # Speedometer bar settings (color)
'bgcolor': "white", # Speedometer background color
'borderwidth': 2, # Speedometer border width
'bordercolor': "gray", # Speedometer border color
'steps': [
{'range': [0, 100], 'color': 'cyan'},
{'range': [100, 200], 'color': 'deepskyblue'},
{'range': [200, 300], 'color': 'royalblue'},
{'range': [300, 400], 'color': 'cornflowerblue'},
{'range': [400, 500], 'color': 'mediumblue'}
], # Settings of color ranges on the speedometer
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 490
} # Threshold settings
}))
# Update the figure layout (background colors, font)
figura.update_layout(
paper_bgcolor="lavender", # Paper background color
font={'color': "darkblue", 'family': "Arial"}, # Font settings
annotations=[
{
'x': 0.5,
'and': 0.4,
'xref': 'paper',
'yref': 'paper',
'showarrow': False,
'text': 'Units', # Label for the units
'font': {'size': 16, 'color': 'darkblue'} # Label font settings
}
]
)
# Display the graph
figura.show()
Python ChatGPT - Artificial Intelligence
# Program - Python - Python ChatGPT - Artificial Intelligence
# Developed by Wilson Borges de Oliveira
# You need to create an "API key" on the OpenAI website
# You need to install the openai library using the command below:
# pip install openai
# -*- coding: cp1252 -*-
import tkinter as tk
from tkinter import messagebox
import openai
# Replace key here
openai.api_key = "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"
def generate(messages):
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=1024,
temperature=0.5
)
return [response.choices[0].message.content, response.usage]
def prepare():
mensagens = [{"role": "system", "content":
"You're a good assistant."}]
question = txt_pergunta.get("1.0","end")
messages.append({"role": "user", "content": str(question)})
reply = generate(messages)
txt_resposta.config(state= "normal")
txt_resposta.delete("1.0","end")
txt_resposta.insert("1.0",responder[0])
txt_resposta.config(state= "disabled")
mensagens.append({"role": "assistant", "content": responder[0]})
def new():
txt_question.delete("1.0","end")
txt_resposta.config(state= "normal")
txt_resposta.delete("1.0","end")
def exit():
tela.destroy()
bodies = tk.Tk()
tela.geometry('1960x800 0 0')
tela.state('zoomed')
screen.title("Python ChatGPT - Artificial Intelligence")
tela['bg'] = "yellow"
lbl_question = tk.Label(tela, text="What do you want?", bg="yellow",
fg="black", font=('Calibri', 12, 'bold'), anchor = "w")
lbl_question.place(x = 20, y = 20, height = 25)
txt_question = tk.Text(tela, font=('Calibri', 20), bg="black", fg="white")
txt_pergunta.place(x = 20, y = 50, width=1320, height=70)
btn_generar = tk.Button(screen, text ="Generate",
bg ='dimgray',foreground='yellow', font=('Calibri', 14),
command = prepare)
btn_gerar.place(x = 570, y = 150, width = 200, height=60)
lbl_response = tk.Label(screen, text="Response:", bg="yellow", fg="black",
font=('Calibri', 12, 'bold'), anchor = "w")
lbl_resposta.place(x = 20, y = 200, height = 25)
txt_resposta = tk.Text(tela, font=('Calibri', 12), bg="black", fg="white")
txt_resposta.place(x = 20, y = 230, width=1300, height=360)
scroll_y = tk.Scrollbar(tela, orient="vertical", command=txt_resposta.yview)
scroll_y.place(x = 1320, y = 230,height=360)
btn_novo = tk.Button(screen, text ="New",
bg ='dimgray',foreground='yellow', font=('Calibri', 14),
command = novo)
btn_novo.place(x = 570, y = 620, width = 80, height=40)
btn_exit = tk.Button(screen, text ="Exit",
bg ='dimgray',foreground='yellow', font=('Calibri', 14),
command = exit)
btn_sair.place(x = 690, y = 620, width = 80, height=40)
txt_pergunta.focus_set()
fabric.mainloop()
Mega-Sena Draw Program
# Program - Mega-Sena Draw
# Allows you to carry out different draws
# Developed by Wilson Borges de Oliveira
import random
import tkinter as tk
from tkinter import *
body = Tk()
screen.title("Mega-Sena Draw - Various Draws")
C = Canvas(tela, bg ="green", height = 600, width = 1000)
C.create_text(500,75, text="Mega-Sena Draw",
anchor="c", fill="yellow", font=('Helvetica','22','bold'))
def draw():
result = []
random.seed()
while len(result) < 6:
r = random.randint(1, 60)
if r not in result:
result.append(r)
result.sort()
x = 140
y = 200
cont = 0
while cont <6:
oval = C.create_oval(x, y, x 110, y 110, fill ="white")
C.create_text(x 52,y 50, text=result[cont],
anchor="c", fill="black", font=('Helvetica','36','bold'))
cont = 1
x = 120
C.pack()
def exit():
tela.destroy()
submitbtn = tk.Button(screen, text ="New Draw",
bg ='gold',foreground='black', font=('Calibri', 12, 'bold'),
command = draw)
submitbtn.place(x = 450, y = 380, width = 150, height=50)
submitbtn = tk.Button(tela, text ="Sair",
bg ='Black',foreground='white', font=('Calibri', 12, 'bold'),
command = exit)
submitbtn.place(x = 820, y = 530, width = 150, height=50)
prize draw()
fabric.mainloop()
Program Calculate Area of Rectangle, Circle and Triangle
# Program - Calculate Area of Rectangle, Circle and Triangle
# Developed by Wilson Borges de Oliveira
import math
import tkinter as tk
from tkinter import *
from tkinter import messagebox
body = Tk()
tela.state('zoomed')
screen.title("Calculate Area of Rectangle, Circle and Triangle")
def calc_square():
try:
var_base = float(txt_base_qd.get().replace(',', '.'))
var_height = float(txt_height_qd.get().replace(',', '.'))
except:
messagebox.showinfo("Warning - Rectangle",
"Please review the numbers entered")
else:
var_area = var_base * var_height
txt_area_qd.delete(0,"end")
txt_area_qd.insert(0, f'{var_area:.2f}'.replace('.', ','))
def calc_circle():
try:
var_radius = float(txt_radius_ci.get().replace(',', '.'))
except:
messagebox.showinfo("Notice - Circle",
"Please review the numbers entered")
else:
var_area = math.pi * var_raio ** 2
txt_area_ci.delete(0,"end")
txt_area_ci.insert(0, f'{var_area:.2f}'.replace('.', ','))
def calc_triang():
try:
var_base = float(txt_base_tr.get().replace(',', '.'))
var_height = float(txt_height_tr.get().replace(',', '.'))
except:
messagebox.showinfo("Warning - Triangle",
"Please review the numbers entered")
else:
var_area = var_base * var_height / 2
txt_area_tr.delete(0,"end")
txt_area_tr.insert(0, f'{var_area:.2f}'.replace('.', ','))
C = Canvas(tela, bg ="gold", width = 1960, height = 800)
#Text
C.create_text(660,35,
text="Calculate Area of Rectangle, Circle and Triangle",
anchor="c", fill="black", font=('Helvetica','22','bold'))
#Square
quadradro = C.create_rectangle(100, 100, 300, 300, outline = "black",
fill = "blue", width = 2)
lbl_form_quad = tk.Label(screen, text ="Area = Base × Height", bg="gold",
fg="black", font=('Calibri', 12, 'bold'))
lbl_form_quad.place(x = 125, y = 310)
lbl_base_qd = tk.Label(tela, text ="Base:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_base_qd.place(x = 125, y = 350, width=90, height = 25)
txt_base_qd = tk.Entry(tela, width = 35, justify=CENTER)
txt_base_qd.place(x = 180, y = 350, width = 75, height = 25)
lbl_altura_qd = tk.Label(tela, text ="Altura:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_altura_qd.place(x = 125, y = 380, width=90, height = 25)
txt_altura_qd = tk.Entry(tela, width = 35, justify=CENTER)
txt_altura_qd.place(x = 180, y = 380, width = 75, height = 25)
btn_quad = tk.Button(tela, text ="Calcular", bg ='yellow',foreground='black',
font=('Calibri', 12, 'bold'), command = calc_quadrado)
btn_quad.place(x = 180, y = 410, width = 75)
lbl_area_qd = tk.Label(tela, text ="Área:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_area_qd.place(x = 125, y = 450, width=90, height = 25)
txt_area_qd = tk.Entry(tela, width = 35, justify=CENTER)
txt_area_qd.place(x = 180, y = 450, width = 75, height = 25)
#Circle
circulo = C.create_oval(580, 100, 780, 300, outline = "black",
fill ="white", width = 2)
lbl_form_circ = tk.Label(fabric, text ="Area = π . r2", bg="gold",
fg="black", font=('Calibri', 12, 'bold'))
lbl_form_circ.place(x = 640, y = 310)
lbl_raio_ci = tk.Label(tela, text ="Radius:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_raio_ci.place(x = 620, y = 350, width=90, height = 25)
txt_raio_ci = tk.Entry(tela, width = 35, justify=CENTER)
txt_raio_ci.place(x = 675, y = 350, width = 75, height = 25)
btn_circ = tk.Button(tela, text ="Calcular", bg ='yellow',foreground='black',
font=('Calibri', 12, 'bold'), command = calc_circulo)
btn_circ.place(x = 675, y = 410, width = 75)
lbl_area_ci = tk.Label(tela, text ="Área:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_area_ci.place(x = 620, y = 450, width=90, height = 25)
txt_area_ci = tk.Entry(tela, width = 35, justify=CENTER)
txt_area_ci.place(x = 675, y = 450, width = 75, height = 25)
#Triangle
triangle = { 'bounds' : [ 1150 , 100 , 1050 , 300 , 1250 , 300 ],
'kind': 'tri', 'fill': True}
C.create_polygon(list(triangulo.values())[0],outline='black',
fill='red', width = 2)
lbl_form_tri2 = tk.Label(tela, text ="___________", bg="gold",
fg="black", font=('Calibri', 12, 'bold'))
lbl_form_tri2.place(x = 1132, y = 307)
lbl_form_tri1 = tk.Label(screen, text="Area = Base × Height", bg="gold",
fg="black", font=('Calibri', 12, 'bold'))
lbl_form_tri1.place(x = 1080, y = 302)
lbl_form_circ3 = tk.Label(tela, text ="2", bg="gold", fg="black",
font=('Calibri', 12, 'bold'))
lbl_form_circ3.place(x = 1170, y = 328)
lbl_base_tr = tk.Label(tela, text ="Base:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_base_tr.place(x = 1080, y = 350, width=90, height = 25)
txt_base_tr = tk.Entry(tela, width = 35, justify=CENTER)
txt_base_tr.place(x = 1135, y = 350, width = 75, height = 25)
lbl_height_tr = tk.Label(screen, text="Height:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_altura_tr.place(x = 1080, y = 380, width=90, height = 25)
txt_altura_tr = tk.Entry(tela, width = 35, justify=CENTER)
txt_altura_tr.place(x = 1135, y = 380, width = 75, height = 25)
btn_triang = tk.Button(tela, text ="Calcular", bg ='yellow',foreground='black',
font=('Calibri', 12, 'bold'), command = calc_triang)
btn_triang.place(x = 1135, y = 410, width = 75)
lbl_area_tr = tk.Label(tela, text ="Área:", bg="gold", fg="black",
font=('Calibri', 12), anchor = 'w')
lbl_area_tr.place(x = 1080, y = 450, width=90, height = 25)
txt_area_tr = tk.Entry(tela, width = 35, justify=CENTER)
txt_area_tr.place(x = 1135, y = 450, width = 75, height = 25)
C.pack()
fabric.mainloop()
Multiplication Tables Program with Audio for Children's Learning
# Multiplication Tables Program with Audio for Children's Learning
# Developed by Wilson Borges de Oliveira
# You need to install the library below:
# pip install pyttsx3
import pyttsx3
engine = pyttsx3.init("sapi5")
engine.setProperty("voice", "brazil")
print ('\n')
n = int(input('Which number do you want the multiplication table for? '))
print ('\n')
for x in range(1,11):
txt_result = str(n) ' X ' str(x) ' = ' str(x * n)
txt_audio = str(n) ' times ' str(x) ' equals ' str(x * n)
print(txt_result)
engine.say(txt_audio)
engine.runAndWait()
engine.stop()
Prisma Program - Light Refraction
# Prisma Program - Refraction of Light
import turtle as pen
from turtle import Screen
bodies = Screen()
screen.title("Prism - Refraction of Light")
def start():
pen.hideturtle()
caneta.speed('fastest')
pen.bgcolor('black')
caneta.pencolor('lightblue')
pen.penup()
pen.goto(POS_TEXT)
pen.write('Prisma - Light Refraction', True, align='left',font=('Calibri',20,'normal'))
pen.goto(0,0)
def draw_prism(x,y,side,color,width):
pen.goto(x,y)
pen.pendown()
pen.pencolor(color)
pen.pensize(width)
pen.backward(side/2)
pen.left(60)
pen.forward(side)
pen.right(120)
pen.forward(side)
pen.right(120)
pen.forward(side/2)
def draw_beam(x,y,length):
pen.penup()
pen.goto(x-length,y OFFSET)
pen.pendown()
pen.pencolor('white')
pen.pensize(15)
pen.goto(x,y OFFSET)
def draw_refraction(color,x,ate_x,y,ate_y):
pen.penup()
pen.goto(x,y OFFSET)
pen.pendown()
pen.pencolor(color)
pen.pensize(15)
pen.goto(ate_x,ate_y)
POS_TEXT = (-130,-190)
DISPLACEMENT = 60
AZULMAGENTA = '#4B0082'
start()
draw_prisma(0,-50,200,"white",2)
caneta.speed('slowest')
draw_beam(0,0,400)
draw_refraction('red',0,400,0,-80)
draw_refraction('orange',0,400,0,-105)
draw_refraction('yellow',0,400,0,-130)
draw_refraction('green',0,400,0,-155)
draw_refraction('mediumblue',0,400,0,-180)
draw_refraction('navy',0,400,0,-205)
draw_refraction(AZULMAGENTA,0,400,0,-230)
pen.done()
Rua Carlos Felipe, 31 - Center
Suzano - SP