Классы в python калькулятор

Python program to create a class which performs basic calculator operations

In this module, we will learn to create a class which performs basic calculator operations in Python.

Being an object-oriented programming language, python stresses on concepts like classes and objects. Classes are required to create objects. They act like a blueprint or template for the creation of objects. Similar types of variables and functions are collected and are placed into a class. We can hence reuse this class to build different objects. Classes make the code more efficient to use. As related data are grouped together, code looks clear and simple enough to understand. Classes are defined with a keyword class.

To create an object we simply use the syntax:

Create a basic calculator using class in python

Problem statement: Write a python program to create a class which performs basic calculator operations.

Let us solve this step by step,

STEP 1: Create a class Calculator and define all the functions of a basic calculator like addition, subtraction, multiplication and division.

class Calculator: def addition(self): print(a + b) def subtraction(self): print(a - b) def multiplication(self): print(a * b) def division(self): print(a / b)

Here, self is used because while calling function using obj.function() (in the following steps), the function will call itself.

STEP 2: Next, take inputs from the user and create an object.

a = int(input("Enter first number:")) b = int(input("Enter first number:")) obj = Calculator()

STEP 3: Lastly, create choices for the user to perform which operation they need and print out the solution.

choice = 1 while choice != 0: print("1. ADD") print("2. SUB") print("3. MUL") print("4. DIV") choice = int(input("Enter your choice:")) if choice == 1: print(obj.addition()) elif choice == 2: print(obj.subtraction()) elif choice == 3: print(obj.multiplication()) elif choice == 4: print(obj.division()) else: print("Invalid choice")
class Calculator: def addition(self): print(a + b) def subtraction(self): print(a - b) def multiplication(self): print(a * b) def division(self): print(a / b) a = int(input("Enter first number:")) b = int(input("Enter first number:")) obj = Calculator() choice = 1 while choice != 0: print("1. ADDITION") print("2. SUBTRACTION") print("3. MULTIPLICATION") print("4. DIVISION") choice = int(input("Enter your choice:")) if choice == 1: print(obj.addition()) elif choice == 2: print(obj.subtraction()) elif choice == 3: print(obj.multiplication()) elif choice == 4: print(obj.division()) else: print("Invalid choice")
Enter first number:3 Enter first number:2 1. ADDITION 2. SUBTRACTION 3. MULTIPLICATION 4. DIVISION Enter your choice:1 5 1. ADDITION 2. SUBTRACTION 3. MULTIPLICATION 4. DIVISION Enter your choice:2 1 1. ADDITION 2. SUBTRACTION 3. MULTIPLICATION 4. DIVISION Enter your choice:3 6 1. ADDITION 2. SUBTRACTION 3. MULTIPLICATION 4. DIVISION Enter your choice:4 1.5 1. ADDITION 2. SUBTRACTION 3. MULTIPLICATION 4. DIVISION Enter your choice:5 Invalid choice

Hence, we have successfully created a class of basic calculator in python.

Читайте также:  Untitled Document

NOTE: There may be other possible methods to solve this problem.

Источник

Python Object-Oriented Programming: Calculator class for basic arithmetic

Write a Python program to create a calculator class. Include methods for basic arithmetic operations.

Sample Solution:

Python Code:

class Calculator: def add(self, x, y): return x + y def subtract(self, x, y): return x - y def multiply(self, x, y): return x * y def divide(self, x, y): if y != 0: return x / y else: return ("Cannot divide by zero.") # Example usage calculator = Calculator() # Addition result = calculator.add(7, 5) print("7 + 5 =", result) # Subtraction result = calculator.subtract(34, 21) print("34 - 21 =", result) # Multiplication result = calculator.multiply(54, 2) print("54 * 2 =", result) # Division result = calculator.divide(144, 2) print("144 / 2 =", result) # Division by zero (raises an error) result = calculator.divide(45, 0) print("45 / 0 output">7 + 5 = 12 34 - 21 = 13 54 * 2 = 108 144 / 2 = 72.0 45 / 0 = Cannot divide by zero.

Explanation:

In the above exercise, we define a class called Calculator with methods add, subtract, multiply, and divide, representing basic arithmetic operations.

The add method performs addition of two numbers, subtract performs subtraction, multiply performs multiplication, and divide performs division. If the denominator is zero, the divide method returns an error message to avoid division by zero.

As an example, we create a Calculator instance, «calculator», and use it to perform various arithmetic operations.

Flowchart: Python - Function that takes a sequence of numbers and determines whether all are different from each other

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Источник

Python Program to Build a Calculator using OOP

Problem: Write a Python program to create a simple calculator i.e a calculator with addition, subtraction, multiplication, and division functionality using object-oriented programming (OOP).

Читайте также:  Css font style medium

To create a basic calculator in python we first need to create a class and define different functionalities like addition, subtraction, etc into separate methods.

After that, we will ask the user to choose what functionality they want to execute through an input, then the user will input the required variables and the respective function will be called to compute the result.

Let’s try to implement it in python.

Source Code:

class Calculator: def add(self, a, b): return a+b def subtract(self, a, b): return a-b def multiply(self, a, b): return a*b def divide(self, a, b): return a/b #create a calculator object my_cl = Calculator() while True: print("1: Add") print("2: Subtract") print("3: Multiply") print("4: Divide") print("5: Exit") ch = int(input("Select operation: ")) #Make sure the user have entered the valid choice if ch in (1, 2, 3, 4, 5): #first check whether user want to exit if(ch == 5): break #If not then ask fo the input and call appropiate methods a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) if(ch == 1): print(a, "+", b, "=", my_cl.add(a, b)) elif(ch == 2): print(a, "-", b, "=", my_cl.subtract(a, b)) elif(ch == 3): print(a, "*", b, "=", my_cl.multiply(a, b)) elif(ch == 4): print(a, "/", b, "=", my_cl.divide(a, b)) else: print("Invalid Input")

calculator in python

In the above program we have used OOP (i.e class and object) to create a basic python calculator.

Make sure that you typecast the inputs into an integer before using them and also check for invalid inputs prior to calling appropriate methods.

If you have any doubts or suggestions then please comment below.

Источник

Калькулятор на python

Здравствуйте, в предыдущей статье я показывал как сделать игру на python, а сейчас мы посмотри как сделать простой калькулятор на python tkinter.

Создаём окно 485 на 550. Размеры не важны, мне понравились такие. Так же указываем, что окно не будет изменяться.

from tkinter import * class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.build() def build(self): pass def logicalc(self, operation): pass def update(): pass if __name__ == '__main__': root = Tk() root["bg"] = "#000" root.geometry("485x550+200+200") root.title("Калькулятор") root.resizable(False, False) app = Main(root) app.pack() root.mainloop() 

Делаем кнопочки

В методе build создаём такой список:

btns = [ "C", "DEL", "*", "=", "1", "2", "3", "/", "4", "5", "6", "+", "7", "8", "9", "-", "+/-", "0", "%", "X^2" ] 

Он отвечает за все кнопки, отображающиеся у нас в окне.

Читайте также:  Златопольский python сборник задач

Мы создали список, теперь проходимся циклом и отображаем эти кнопки. Для этого в том же методе пишем следующее:

x = 10 y = 140 for bt in btns: com = lambda x=bt: self.logicalc(x) Button(text=bt, bg="#FFF", font=("Times New Roman", 15), command=com).place(x=x, y=y, width=115, height=79) x += 117 if x > 400: x = 10 y += 81 

Замечательно, у нас есть кнопочки. Добавляем надпись с выводом результата. Я хочу что бы текст был слева, следовательно, аттрибутов выравнивания текста писать не нужно.

self.formula = "0" self.lbl = Label(text=self.formula, font=("Times New Roman", 21, "bold"), bg="#000", foreground="#FFF") self.lbl.place(x=11, y=50) 

Пишем логику

def logicalc(self, operation): if operation == "C": self.formula = "" elif operation == "DEL": self.formula = self.formula[0:-1] elif operation == "X^2": self.formula = str((eval(self.formula))**2) elif operation == "=": self.formula = str(eval(self.formula)) else: if self.formula == "0": self.formula = "" self.formula += operation self.update() def update(self): if self.formula == "": self.formula = "0" self.lbl.configure(text=self.formula) 

Так, как у нас нет ввода с клавиатуры, мы можем позволить себе сделать так, просто проверить на спец. кнопки (C, DEL, =) и в остальных случаях просто добавить это к формуле.

У этого калькулятора множество недочетов, но мы и не стремились сделать его идеальным.

Полный код моей версии калькулятора:

from tkinter import * class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.build() def build(self): self.formula = "0" self.lbl = Label(text=self.formula, font=("Times New Roman", 21, "bold"), bg="#000", foreground="#FFF") self.lbl.place(x=11, y=50) btns = [ "C", "DEL", "*", "=", "1", "2", "3", "/", "4", "5", "6", "+", "7", "8", "9", "-", "(", "0", ")", "X^2" ] x = 10 y = 140 for bt in btns: com = lambda x=bt: self.logicalc(x) Button(text=bt, bg="#FFF", font=("Times New Roman", 15), command=com).place(x=x, y=y, width=115, height=79) x += 117 if x > 400: x = 10 y += 81 def logicalc(self, operation): if operation == "C": self.formula = "" elif operation == "DEL": self.formula = self.formula[0:-1] elif operation == "X^2": self.formula = str((eval(self.formula))**2) elif operation == "=": self.formula = str(eval(self.formula)) else: if self.formula == "0": self.formula = "" self.formula += operation self.update() def update(self): if self.formula == "": self.formula = "0" self.lbl.configure(text=self.formula) if __name__ == '__main__': root = Tk() root["bg"] = "#000" root.geometry("485x550+200+200") root.title("Калькулятор") root.resizable(False, False) app = Main(root) app.pack() root.mainloop() 

Источник

Оцените статью