jueves, 24 de junio de 2021

Ejercicios Practicos Python

En el video podras ver la solucion a estos ejercicios para practicar con Python.

1. Mostrar el importe del IVA de un articulo con un valor de 80 junto con su precio final.

2. Crea una variable numerica, si esta entre 0 y 20 mostrar un mensaje.

3. Mostrar con un bucle while los numeros del 10 al 50.

4. Mostrar con un bucle for los numeros del 200 al 300.

5. Generar un rango entre 0 y 10.

6. Generar un rango desde 0 hasta la longitud de toda esta cadena.

7. Dada una cadena indicar si es palindromo o no.

8. Definir una funcion que calcule la longitud de una cadena dada.

9. Definir una funcion que calcule la suma y multiplicacion de una lista.

10. Definir funcion que muestre una cadena al reves.

11. Definir funcion que indique si el caracter pasado es vocal o no.

12. Definir funcion para devolver un caracter x veces.



domingo, 20 de junio de 2021

Crea ejecutable para poder distribuir tu aplicacion Python

 Crear fichero ejecutable para windows, para poder distribuir la aplicacion Python entre diferentes pc sin que tengan que tener instalado Python.




sábado, 19 de junio de 2021

Ejercicio practico, Agenda con Tkinter y SQLite en Python

 


#Script principal

from tkinter import *
from tkinter import messagebox
from baseDatos import *
ANCHO = 560
ALTO = 540
POSX = 300
POSY = 400
anchoAlto = str(ANCHO)+"x"+str(ALTO)
posicionX = "+"+str(POSX)
posicionY = "+"+str(POSY)
colorVentana = "blue"
colorLetra = "white"


def mostrarMensaje(titulomensaje):
    messagebox.showinfo(titulo, mensaje)


def limpiarDatos():
    nombre.set("")
    apellidos.set("")
    telefono.set("")
    email.set("")
    ID.set(0)
    text.delete(1.0, END)


def guardar():
    crearTabla()
    if((nombre.get() == ""or (apellidos.get() == "")):
        mostrarMensaje("Error""Debes rellenar los datos")
    else:
        datos = nombre.get(), apellidos.get(), telefono.get(), email.get()
        mostrarMensaje("Guardar""Contacto guardado")
        insertar(datos)
        limpiarDatos()
        mostrar()


def actualizar():
    crearTabla()
    if((ID.get() == ""or (ID.get() == 0or (nombre.get() == "")):
        mostrarMensaje("Error""Debes rellenar los datos")
    else:
        try:
            modificar(ID.get(), nombre.get(), apellidos.get(),
                      telefono.get(), email.get())
            mostrarMensaje("Modificar""Contacto modificado")
            limpiarDatos()
            mostrar()
        except:
            mostrarMensaje("Error""Identificador no encontrado")


def eliminar():
    if((ID.get() == ""or (ID.get() == 0)):
        mostrarMensaje("Error""Debes insertar un identificador valido")
    else:
        try:
            borrar(ID.get())
            mostrarMensaje("Borrar""Contacto borrado")
            limpiarDatos()
            mostrar()
        except:
            mostrarMensaje("Error""Identificador no encontrado")


def mostrar():
    listado = consultar()
    text.delete(1.0, END)
    text.insert(INSERT, "ID\tNombre\tApellidos\t\tTelefono\tEmail\n")
    for elemento in listado:
        id = elemento[0]
        nombre = elemento[1]
        apellidos = elemento[2]
        telefono = elemento[3]
        email = elemento[4]
        text.insert(INSERT, id)
        text.insert(INSERT, "\t")
        text.insert(INSERT, nombre)
        text.insert(INSERT, "\t")
        text.insert(INSERT, apellidos)
        text.insert(INSERT, "\t\t")
        text.insert(INSERT, telefono)
        text.insert(INSERT, "\t")
        text.insert(INSERT, email)
        text.insert(INSERT, "\n")


ventana = Tk()
ventana.config(bg=colorVentana)
ventana.geometry(anchoAlto+posicionX+posicionY)
ventana.title("Agenda")
frame = Frame()
frame.config(width=ANCHO, height=ALTO)
frame.config(bg=colorVentana)
frame.pack()
# variables
ID = IntVar()
nombre = StringVar()
apellidos = StringVar()
telefono = StringVar()
email = StringVar()
# widgets
etiquetaID = Label(frame, text="ID: ").place(x=50y=50)
cajaID = Entry(frame, textvariable=ID).place(x=130y=50)
etiquetaNombre = Label(frame, text="Nombre: ").place(x=50y=90)
cajaNombre = Entry(frame, textvariable=nombre).place(x=130y=90)
etiquetaApellidos = Label(frame, text="Apellidos: ").place(x=50y=130)
cajaApellidos = Entry(frame, textvariable=apellidos).place(x=130y=130)
etiquetaTelefono = Label(frame, text="Telefono: ").place(x=50y=170)
cajaTelefono = Entry(frame, textvariable=telefono).place(x=130y=170)
etiquetaEmail = Label(frame, text="Email: ").place(x=50y=210)
cajaEmail = Entry(frame, textvariable=email).place(x=130y=210)
text = Text(frame)
text.place(x=50y=240width=500height=200)
botonAñadir = Button(frame, text="Añadir",
                     command=guardar).place(x=150y=500)
botonBorrar = Button(frame, text="Borrar",
                     command=eliminar).place(x=200y=500)
botonConsultar = Button(frame, text="Consultar",
                        command=mostrar).place(x=250y=500)
botonModificar = Button(frame, text="Actualizar",
                        command=actualizar).place(x=320y=500)
ventana.mainloop()

#Script base de datos

import sqlite3


def conectar():
    conexion = sqlite3.connect("agenda.db")
    cursor = conexion.cursor()
    return conexion, cursor


def crearTabla():
    conexion, cursor = conectar()
    sql = """
        CREATE TABLE IF NOT EXISTS agenda(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
            nombre VARCHAR(20) NOT NULL,
            apellidos VARCHAR(20) NOT NULL,
            telefono VARCHAR(14) NOT NULL,
            email VARCHAR(20) NOT NULL
        )
    """
    if(cursor.execute(sql)):
        print("Tabla creada")
    else:
        print("No se pudo crear la tabla")
    conexion.close()


def insertar(datos):
    conexion, cursor = conectar()
    sql = """
    INSERT INTO agenda(nombre,apellidos,telefono,email) VALUES (?,?,?,?)
    """
    if(cursor.execute(sql, datos)):
        print("Datos guardados")
    else:
        print("No se pudieron guardar los datos")
    conexion.commit()
    conexion.close()


def consultar():
    conexion, cursor = conectar()
    sql = "SELECT id,nombre,apellidos,telefono,email from agenda"
    cursor.execute(sql)
    listado = []
    for fila in cursor:
        listado.append(fila)
        # print("ID = ", fila[0])
        # print("Nombre = ", fila[1])
        # print("Telefono = ", fila[2], "\n")
    listado.sort()
    conexion.close()
    return listado


def modificar(idnombreapellidostelefonoemail):
    conexion, cursor = conectar()
    sql = "UPDATE agenda SET nombre='"+nombre+"',apellidos='"+apellidos + \
        "', telefono='"+telefono+"', email='"+email+"' where ID="+str(id)
    cursor.execute(sql)
    cursor.close()
    conexion.commit()
    conexion.close()


def borrar(id):
    conexion, cursor = conectar()
    sql = "DELETE from agenda where ID="+str(id)
    cursor.execute(sql)
    cursor.close()
    conexion.commit()
    conexion.close()