2 votes

How to calculate the percentage in a Python calculator with the eval function?

I have written a calculator in python with PyQt5 and so far all the operations are performed correctly except the percentage, for the data evaluation I use eval, I appreciate your help. The code used is the following:

 import sys, math

from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QMessageBox

# Cargar archivo ui
form_class = uic.loadUiType("Calculadora02.ui")[0]


def num(self, s):
    self.pantallaresultado.insertPlainText(s)


def operador(self, op):
    div = self.pantallaresultado.toPlainText()
    if (validarExpresion(div)):
        nuevo = div + op
        pantalla(self, nuevo)


def pantalla(self, a):
    self.pantallaresultado.clear()
    self.pantallaresultado.insertPlainText(a)


def validarExpresion(div):
    ultimo = div[len(div) - 1]
    simbolos = "+-*/.%"
    encontro = True
    for i in range(len(simbolos)):
        if (simbolos[i] == ultimo):
            encontro = False
            break
    return encontro


def calcular(self, div):
    if (len(div) > 2):
        resultado = eval(str(div))
        pantalla(self, str(resultado))

    else:
        pantalla(self, "Ingrese una expresion para calcular:")


class MyWindowClass(QtWidgets.QMainWindow, form_class):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.btn1.clicked.connect(self.btnuno)
        self.btn2.clicked.connect(self.btndos)
        self.btn3.clicked.connect(self.btntres)
        self.btn4.clicked.connect(self.btncuatro)
        self.btn5.clicked.connect(self.btncinco)
        self.btn6.clicked.connect(self.btnseis)
        self.btn7.clicked.connect(self.btnsiete)
        self.btn8.clicked.connect(self.btnocho)
        self.btn9.clicked.connect(self.btnnueve)
        self.btn0.clicked.connect(self.btncero)
        self.btnpunto.clicked.connect(self.btnpnto)
        self.btnporcentaje.clicked.connect(self.btnprcentaje)
        self.btnmas.clicked.connect(self.btnms)
        self.btnmenos.clicked.connect(self.btnmnos)
        self.btnmultiplicasion.clicked.connect(self.btnmltiplicasion)
        self.btndivision.clicked.connect(self.btndvision)
        self.btndescontar.clicked.connect(self.btndscontar)
        self.btnclear.clicked.connect(self.btnlimpiar)
        self.btnpar1.clicked.connect(self.btnparuno)
        self.btnpar2.clicked.connect(self.btnpardos)
        self.btnpotencia.clicked.connect(self.btnptencia)
        self.btnraiz.clicked.connect(self.btnriz)
        self.btncalcular.clicked.connect(self.btnclcular)

    # Evento de los botones del 1-0 y parentesis
    def btnuno(self):
        return num(self, "1")

    def btndos(self):
        return num(self, "2")

    def btntres(self):
        return num(self, "3")

    def btncuatro(self):
        return num(self, "4")

    def btncinco(self):
        return num(self, "5")

    def btnseis(self):
        return num(self, "6")

    def btnsiete(self):
        return num(self, "7")

    def btnocho(self):
        return num(self, "8")

    def btnnueve(self):
        return num(self, "9")

    def btncero(self):
        return num(self, "0")

    def btnparuno(self):
        return num(self, "(")

    def btnpardos(self):
        return num(self, ")")

    def btnpnto(self):
        return num(self, ".")

    def btnprcentaje(self):
        p = self.pantallaresultado.toPlainText()
        r=p
        pantalla(self,str(r))

    def btnms(self):
        return num(self, "+")

    def btnmnos(self):
        return num(self, "-")

    def btnmltiplicasion(self):
        return num(self, "*")

    def btndvision(self):
        return num(self, "/")

    def btndscontar(self):
        p = self.pantallaresultado.toPlainText()
        pa = ""
        for i in range(len(p)):
            if (i == (len(p) - 1)):
                pa += ""
            else:
                pa += p[i]
                pantalla(self, str(pa))

    def btnlimpiar(self):
        self.pantallaresultado.clear()

    def btnclcular(self):
        div = self.pantallaresultado.toPlainText()
        calcular(self, div)

    def btnptencia(self):
        p = self.pantallaresultado.toPlainText()
        r = pow(float(p), 2)
        pantalla(self, str(r))

    def btnriz(self):
        p = self.pantallaresultado.toPlainText()
        r = math.sqrt(float(p))
        pantalla(self, str(r))

        # Evento cerrar ventana

    def closeEvent(self):
        # Your desired functionality here
        print('Close button pressed')
        import sys
        sys.exit(0)

    def buttonClicked(self, e):
        QMessageBox.information(self, 'Events - Slot', 'click en Button 1.')

    def closeEvent(self, event):
        reply = QMessageBox.question(self, '¡¡¡Advertencia!!!', "Realmente desea cerrar la aplicacion",
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()


app = QtWidgets.QApplication(sys.argv)
MainCalculadora02 = MyWindowClass(None)
MainCalculadora02.show()
app.exec_()

1voto

ACMM Points 19

Basically it would be:

 num1 = input("Número: ")
num2 = input("Porcentagem: ")

def porcentagem(num1, num2):
    n1 = int(num1)
    n2 = int(num2)

    res = eval("n1 * n2 / 100)")

    print(f"{n1} x {n2}% = {res}")

porcentagem(num1, num2)

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X