How to make calculator in python

Калькулятор на 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" ] 

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

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

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, =) и в остальных случаях просто добавить это к формуле.

Читайте также:  Javascript math random целое число

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

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

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() 

Источник

How to Make a Calculator With Python

A simple calculator in Python is an excellent project for beginners and advanced programmers. The process of making a calculator involves some basic programming concepts. This includes taking user input, conditional statements, and functions.

This guide provides step-by-step instructions to make a calculator with Python.

How to Make a Calculator With Python

  • Python 3 installed.
  • An IDE or code editor to write the code for the project.
  • A way to run the code (IDE or the command line/terminal).

Step 1: Create a File for the Calculator

The first step covers the following skills:

Start by creating a project directory and a file for the calculator code. On Linux, follow the steps below:

1. Open the terminal (CTRL+Alt+T).

2. Create the project directory with the mkdir command:

4. Create a file with a .py extension and open it with a text editor, such as nano:

Keep the file open and proceed to the next step.

Step 2: Prompt for User Input

The second step covers the following:

  • Writing comments in Python.
  • Taking user input.
  • Converting user input to a desired data type.
  • Saving and running the code.

The program enables the user to enter two numbers for a simple calculation. Do the following:

1. Fetch a user’s input with Python’s built-in input() method and save the entry into two variables. Add the following code to the calculator.py file you opened in the previous step:

# Prompt for user input a = input("Enter the first number: ") b = input("Enter the second number: ")

The input() method accepts any entry type and saves the entered information as a string.

2. Limit user entry to numbers. If performing calculations with whole numbers (integer calculations), encase the input() method in int() to convert the input into an integer:

# Prompt for user input a = int(input("Enter the first number: ")) b = int(input("Enter the second number: "))

The better option is to use float() to perform more precise calculations. To allow decimal calculations, convert the user entry into floating point numbers:

# Prompt for user input a = float(input("Enter the first number: ")) b = float(input("Enter the second number: "))

Python calculator input numbers code

In both cases, the program throws an error if the user enters anything that is not a number.

3. Save the file and close the editor (for nano, use CTRL+X, confirm with Y, and hit Enter).

4. Run the program to see how it works:

Python enter two numbers calculator terminal output

Test multiple times to see the behavior for different user entries.

Note: input() function can also be used to read from stdin in Python. Learn more in our article How to Read From stdin in Python.

Step 3: Perform Operations

The third step covers the following concepts:

Decide what kind of operations the calculator performs. Below is a brief table with the available built-in operators in Python.

Operator Description
+ Addition
Subtraction
* Multiplication
** Power (exponent)
/ Division
// Floor division
% Modulo (division remainder)

To create and test different operations:

1. Open the calculator.py file again:

2. Add the following code to the file to print the result of different operations:

# Prompt for user input a = float(input("Enter the first number: ")) b = float(input("Enter the second number: ")) # Perform operations print("Sum: <> + <> = <>".format(a,b,a+b)) print("Difference: <> - <> = <>".format(a,b,a-b)) print("Product: <> * <> = <>".format(a,b,a*b)) print("Quotient: <> / <> = <>".format(a,b,a/b)) print("Power: <>^<> = <>".format(a,b,a**b)) print("Division with remainder: <> / <> = <> Remainder: <>".format(a,b,a//b,a%b))

Python calculator operations print code

The program takes the two input numbers and prints the result of different calculations using string concatenation.

3. Save and close the file.

4. Run the program to test:

Python calculator operations print terminal output

Enter any two numbers to see the result of all the operations.

Step 4: Add Conditions

The fourth step covers these functionalities:

  • Multiline printing.
  • Conditional statements.
  • Catching errors with try except blocks.

Conditional statements in Python help control the program flow based on a value. Instead of performing all operations on the two input numbers, allow users to choose and check the input using a conditional statement.

A multiline comment enables a quick way to create a menu with choices.

Change the code in the calculator.py file to match the following:

# First part: Prompt for user input a = float(input("Enter the first number: ")) b = float(input("Enter the second number: ")) print(""" Choose an operation from the list: 1. Addition 2. Subtraction 3. Multiplication 4. Exponentiation 5. Division 6. Division with remainder """) op = int(input("Enter the choice number: ")) # Second part: Perform operations based on input if op == 1: print("Sum: <> + <> = <>".format(a,b,a+b)) elif op == 2: print("Difference: <> - <> = <>".format(a,b,a-b)) elif op == 3: print("Product: <> * <> = <>".format(a,b,a*b)) elif op == 4: print("Power: <>^<> = <>".format(a,b,a**b)) elif op == 5: try: print("Quotient: <> / <> = <>".format(a,b,a/b)) except: print("Division by 0 not possible!") elif op == 6: try: print("Division with remainder: <> / <> = <> Remainder: <>".format(a,b,a//b,a%b)) except: print("Divsion by 0 not possible!") else: print("No such choice!")

The code adds new features and functionalities. Below is a brief overview:

  • The first part of the code generates a simulated user menu with choices (multiline comments). The program saves the user input into variables (first number, second number, and operation).

Python calculator user input and menu code

  • The second part of the code takes the user input variables and performs a calculation based on the input. The final else block prints a message if a user chooses something that’s not an option in the program.
  • In the case of division by zero, the program uses a try except block to catch the program error and prints a descriptive error message.

Python calculator division by zero try except code

Save and run the code to see how the program works:

Python calculator with menu terminal output

Run the code several times for different user inputs to see how the output and behavior differ.

Step 5: Create Functions

The fifth step in the calculator program covers the following:

Separate the code into logical units and use a recursive function to loop the program. Modify the code in the calculator.py file to match the following:

def prompt_menu(): a = float(input("Enter the first number: ")) b = float(input("Enter the second number: ")) print(""" Choose an operation from the list: 1. Addition 2. Subtraction 3. Multiplication 4. Exponentiation 5. Division 6. Division with remainder """) op = int(input("Enter the choice number: ")) return a, b, op def calculate(): a, b, op = prompt_menu() if op == 1: print("Sum: <> + <> = <>".format(a,b,a+b)) elif op == 2: print("Difference: <> - <> = <>".format(a,b,a-b)) elif op == 3: print("Product: <> * <> = <>".format(a,b,a*b)) elif op == 4: print("Power: <>^<> = <>".format(a,b,a**b)) elif op == 5: try: print("Quotient: <> / <> = <>".format(a,b,a/b)) except: print("Division by 0 not possible!") elif op == 6: try: print("Division with remainder: <> / <> = <> Remainder: <>".format(a,b,a//b,a%b)) except: print("Divsion by 0 not possible!") else: print("No such choice!") loop() def loop(): choice = input("Do you want to continue? (Y,N): ") if choice.upper() == "Y": calculate() elif choice.upper() == "N": print("Goodbye!") else: print("Invalid input!") loop() calculate()

The code has three distinct functions:

  • The prompt_menu() function contains the user menu and returns the two input numbers and selected operation.
  • The calculate() function uses the prompt_menu() function to gather the user input and calculate based on the provided information.
  • The loop() function creates a loop menu where the user chooses whether to continue using the program. In case of invalid input, the function recursively calls itself and reruns the function. The final line in the calculate() function calls the loop() function.

Python recursive function loop code

After the function definitions, the program calls the calculate() function to run the program loop.

Save the code and run the program with the following:

Python calculator loop terminal output

The program loops until the user enters N or n to exit the program.

After working through the steps in this guide, you have a fully-functional calculator program written in Python. Improving the existing code or taking a completely different approach is possible.

Once ready, use Git to store and manage your project.

Источник

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