- Calculator Program in Python
- Prerequisites
- Accept/Prompt Input from User
- Defining and using Operators
- Including condition statement to make the program as User’s choice
- References
- Калькулятор на python
- Делаем кнопочки
- Пишем логику
- Полный код моей версии калькулятора:
- Program calculator in python
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Python Program to Make a Simple Calculator
- Example: Simple Calculator by Using Functions
Calculator Program in Python
Python programming is a great tool to evaluate and make manipulations. In this article, We will be learning a simple command-line calculator program in Python 3.
We’ll be using mathematical operators, Conditional statements, functions and handle user input to make our calculator.
Prerequisites
The system should have Python 3 installed on the local computer and have a programming environment set up on the machine.
Accept/Prompt Input from User
We’ll be accepting input from the user. To serve this purpose, we will be using the input() function of Python. For this program, we will let the user input two numbers, so let’s have the program for prompt of the two numbers.
num_1 = input('Enter your first number: ') num_2 = input('Enter your second number: ')
Enter your first number: 10 Enter your second number: 5
We should save the program before we run it. You should be able to type into the terminal window in response to each prompt.
Defining and using Operators
Now, let’s add the operators such as addition, multiplication, division and subtraction to our Calculator program.
num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: ')) # Addition print('<> + <> = '.format(num_1, num_2)) print(num_1 + num_2) # Subtraction print('<> - <> = '.format(num_1, num_2)) print(num_1 - num_2) # Multiplication print('<> * <> = '.format(num_1, num_2)) print(num_1 * num_2) # Division print('<> / <> = '.format(num_1, num_2)) print(num_1 / num_2) # The format() will help out output look descent and formatted.
Enter your first number: 15 Enter your second number: 10 15 + 10 = 25 15 - 10 = 05 15 * 10 = 150 15 / 10 = 1.5
If you have a look at the above output, we can notice that as soon as the user enters num_1 as 15 and num_2 as 10 , all the operations of the calculator gets executed.
If we want to limit the program to only perform one operation at a time, we’ll have to use conditional statements and make the entire calculator program to be user’s choice based operation program.
Including condition statement to make the program as User’s choice
So, we will start by adding some information at the top of the program, along with a choice to make, in order to make the user understand what he/she is supposed to choose.
choice = input(''' Please select the type of operation you want to perform: + for addition - for subtraction * for multiplication / for division ''') num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: ')) if choice == '+': print('<> + <> = '.format(num_1, num_2)) print(num_1 + num_2) elif choice == '-': print('<> - <> = '.format(num_1, num_2)) print(num_1 - num_2) elif choice == '*': print('<> * <> = '.format(num_1, num_2)) print(num_1 * num_2) elif choice == '/': print('<> / <> = '.format(num_1, num_2)) print(num_1 / num_2) else: print('Enter a valid operator, please run the program again.')
Please select the type of operation you want to perform: + for addition - for subtraction * for multiplication / for division * Please enter the first number: 10 Please enter the second number: 40 10 * 40 = 400
References
Калькулятор на 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, =) и в остальных случаях просто добавить это к формуле.
У этого калькулятора множество недочетов, но мы и не стремились сделать его идеальным.
Полный код моей версии калькулятора:
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()
Program calculator in python
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Python Program to Make a Simple Calculator
To understand this example, you should have the knowledge of the following Python programming topics:
Example: Simple Calculator by Using Functions
# This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: # take input from the user choice = input("Enter choice(1/2/3/4): ") # check if choice is one of the four options if choice in ('1', '2', '3', '4'): try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) except ValueError: print("Invalid input. Please enter a number.") continue if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) # check if user wants another calculation # break the while loop if answer is no next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break else: print("Invalid Input")
Select operation. 1.Add 2.Subtract 3.Multiply 4.Divide Enter choice(1/2/3/4): 3 Enter first number: 15 Enter second number: 14 15.0 * 14.0 = 210.0 Let's do next calculation? (yes/no): no
In this program, we ask the user to choose an operation. Options 1, 2, 3, and 4 are valid. If any other input is given, Invalid Input is displayed and the loop continues until a valid option is selected.
Two numbers are taken and an if. elif. else branching is used to execute a particular section. User-defined functions add() , subtract() , multiply() and divide() evaluate respective operations and display the output.