Калькулятор
Многие программисты стараются изучать языки программирования с помощью написания достаточно простых программ. Один из вариантов – написание калькулятора. Конечно, можно посчитать в отладчике Python или запустив консоль. Но гораздо лучше написать на python свой калькулятор с графическим интерфейсом.
Считаем в консоле
Чтобы посчитать математические выражения можно запустить консоль. Запустить python. После этого набираем математические выражения и получаем ответ. Для этого даже не надо уметь программировать.

Делаем простой калькулятор
Лучше всего закреплять свои знания по программированию с помощью написания простых программ. Таких приложений можно придумать много – календарь, программа для хранения заметок, получение прогноза погоды.
Можно написать программу, которая делает скриншоты и сохраняет полученные изображения в папку. В любом случае, надо выбрать какое-нибудь не сложное задание, чтобы не закопаться в нем. Потом его можно будет расширить и сделать по-настоящему полезное приложение.
В нашем случае мы разберем, как создать простой графический калькулятор на Python 3. Для реализации графического интерфейса воспользуемся стандартным пакетом Tkinter. Он входит в состав Python 3. Соответственно, если у вас установлен Python, то дополнительно не надо ничего устанавливать.
В первых строках файла calculator.py подключаем библиотечные функции:
- Tkinter для графического интерфейса;
- Decimal для вычислений с большей точность, так как точности float не достаточно.
Импорт библиотек и исходные данные
Создаем окно приложения — объект Tk с заголовком Calculator. Во вложенном кортеже buttons будут храниться обозначения для кнопок. В список stack будем добавлять введенные числа и операции, которые надо совершить. activeStr предназначен для хранения набираемого числа.
Вычисление результата
Функция calculate получает из списка stack операнды и операцию которую над ними надо произвести. Результат отображается в надписи label. Получать из списка строки будем с помощью метода pop.
Обработка нажатия
В функции click выполняется обработка нажатой клавиши. В качестве ее аргумента передается текст, отображаемый на кнопке, которую нажали. Хотелось бы хранить вводимое значение прямо в надписи, а не создавать для этого отдельную переменную. Но так не получается из-за алгоритма работы. После того как посчитан результат, он записывается в надписи. При попытке после этого начать вводить новое число, оно бы дописывало прежний результат.
В списке с операторами и командами для калькулятора не обязательно их будет 3. Но при обработке с помощью метода pop, будут рассматриваться 3 последних введенных значения. А после проведения расчета список очистится. Далее в него добавляется полученный результат, на случай если пользователь нажмет на калькуляторе клавишу операции сразу, а не будет вводить новое число.
Внешний вид
Теперь займемся оформлением внешнего вида калькулятора и зададим обработку нажатия кнопок. Создаем надпись для вывода набираемых значений и результатов. В цикле создаем кнопки. Расположение кнопок и надписи осуществляется в табличном виде с помощью упаковщика grid. И в завершении запускаем цикл обработки событий mainloop.
У надписи выставлена ширина 35, для того, чтобы оформление кнопок подстраивалось под надпись. И в результате кнопки при этом значении лучше выглядят.
Для того, чтобы кнопки правильно работали, пришлось для каждой из кнопок создать свою функцию с помощью lambda.
По аналогии приведенного кода python калькулятора можно сдель, допустим, календарь. Для этого надо будет запрашивать текущую дату у операционной системы. Открывать нужный месяц, рассчитывать какие числа выпадут на понедельники, какой год високосный. Сделать возможность менять год и месяцы.
How To Make a Calculator Program in Python 3

The Python programming language is a great tool to use when working with numbers and evaluating mathematical expressions. This quality can be utilized to make useful programs.
This tutorial presents a learning exercise that outlines how to make a command-line calculator program in Python 3. This calculator will be able to perform only basic arithmetic, but the final step of this guide serves as a starting point for how you might improve the code to create a more robust calculator.
We’ll be using math operators, variables, conditional statements, functions, and handle user input to make our calculator.
Prerequisites
For this tutorial, you should have Python 3 installed on your local computer and have a programming environment set up on the machine. If you need to install Python or set up the environment, you can do so by following the appropriate guide for your operating system.
Step 1 — Prompt Users for Input
Calculators work best when a human provides equations for the computer to solve. You’ll start writing your program at the point where the human enters the numbers that they would like the computer to work with.
First, you’ll create a file for your program. For this example, we’ll use the text editor nano and name the file calculator.py :
Next, you’ll add contents to this file to run your program. For this program, you’ll have the user input two numbers, so instruct the program to prompt the user for two numbers. You can do this by using Python’s built-in input() function to accept user-generated input from the keyboard. Inside of the parentheses of the input() function you can pass a string to prompt the user, and then assign the user’s input to a variable. Keep in mind that when asking for input, it can be helpful to include a space at the end of your string so that there is a space between the user’s input and the prompting string:
After writing two lines, you should save the program before running it. If you’re using nano , you can exit by pressing CTRL + X then Y and ENTER .
Run your program with the following command:
This will begin your program’s prompts and you can respond in the terminal window:
If you run this program a few times and vary your input, you’ll notice that you can enter whatever you want when prompted, including words, symbols, whitespace, or the enter key. This is because input() takes data in as strings and doesn’t know that you’re looking for numbers.
You’ll want to use numbers in this program for two reasons:
- to enable the program to perform mathematical calculations
- to validate that the user’s input is a numerical string
Depending on the needs of your calculator, you may want to convert the string that comes in from the input() function to either an integer or a float. For this tutorial, whole numbers suit our purpose, so wrap the input() function in the int() function to convert the input to the integer data type:
Now, if you run the program and input two integers you won’t run into an error:
But, if you enter letters, symbols, or any other non-integers, you’ll encounter the following error:
So far, you’ve set up two variables to store user input in the form of integer data types. You can also experiment with converting the input to floats.
Step 2 — Adding Operators
Before the program is complete, you’ll add a total of four mathematical operators: + for addition, — for subtraction, * for multiplication, and / for division.
As you build out the program, you’ll want to make sure that each part is functioning correctly, so start with setting up addition. You’ll add the two numbers within a print function so that the person using the calculator will be able to see the contents:
Run the program and type in two numbers when prompted to ensure that it is working as expected:
The output shows that the program is working correctly. Now, add some more context for the user to be fully informed throughout the runtime of the program. To do this, use string formatters to help properly format the text and provide feedback. You want the user to receive confirmation about the numbers they are entering and the operator that is being used alongside the produced result:
Now, when you run the program, you’ll have extra output that will let the user confirm the mathematical expression that is being performed by the program:
Using the string formatters provides the users with more feedback.
At this point, you can add the rest of the operators to the program with the same format used for addition:
Here, you’re adding the remaining operators, — , * , and / into the program above. If you run the program at this point, the program will execute all of the operations above. However, you want to limit the program to perform one operation at a time. To do this, you’ll use conditional statements.
Step 3 — Adding Conditional Statements
The goal of the calculator.py program is for the user to be able to choose among the different operators. Start by adding some information at the top of the program, along with a choice to make, so that the person knows what to do.
Write a string on a few different lines by using triple quotes:
This program uses each of the operator symbols for users to make their choice, so if the user wants division to be performed, they will type / . You could choose whatever symbols you want, though, like 1 for addition , or b for subtraction .
Because you’re asking users for input, you want to use the input() function. Put the string inside of the input() function, and pass the value of that input to a variable, which you’ll name operation :
At this point, if you run the program nothing will happen, no matter what you input at the first prompt. To correct this, add some conditional statements into the program. Because of how you have structured the program, the if statement will be where the addition is performed, there will be 3 else-if or elif statements for each of the other operators, and the else statement will be put in place to handle an error if the user did not input an operator symbol:
To walk through this program, first it prompts the user to put in an operation symbol. For example, say the user inputs * to multiply. Next, the program asks for two numbers, and the user inputs 58 and 40 . At this point, the program shows the equation performed and the product:
Because of how you structured the program, if the user enters % when asked for an operation at the first prompt, they won’t receive feedback to try again until after entering numbers. You may want to consider other possible options for handling various situations.
At this point, you have a fully functional program, but you can’t perform a second or third operation without running the program again. The next step involves defining a few functions to add this functionality to the program.
Step 4 — Defining Functions
To handle the ability to perform the program as many times as the user wants, you’ll define some functions. First, put your existing code block into a function. Name the function calculate() and add an additional layer of indentation within the function itself. To ensure the program runs, you’ll also call the function at the bottom of the file:
Next, create a second function made up of more conditional statements. In this block of code, you want to give the user the choice as to whether they want to calculate again or not. You can base this off of the calculator conditional statements, but in this case, you’ll only have one if , one elif , and one else to handle errors.
Name this function again() , and add it after the def calculate(): code block:
Although there is some error-handling with the else statement above, you could probably make it clearer to accept, say, a lower-case y and n in addition to the upper-case Y and N . To do that, add the string function str.upper() :
At this point, you should add the again() function to the end of the calculate() function so that it will trigger the code that asks the user whether or not they would like to continue:
You can now run your program with python calculator.py in your terminal window and you’ll be able to calculate as many times as you would like.
Step 5 — Improving the Code
Now you have a nice, fully functional program. However, there is a lot more you can do to improve this code. You can add a welcome function, for example, that welcomes people to the program at the top of the program’s code, like this:
There are opportunities to introduce more error-handling throughout the program. For starters, you can ensure that the program continues to run even if the user types plankton when asked for a number. As the program is right now, if number_1 and number_2 are not integers, the user will get an error and the program will stop running. Also, for cases when the user selects the division operator ( / ) and types in 0 for their second number ( number_2 ), the user will receive a ZeroDivisionError: division by zero error. For this, you may want to use exception handling with the try . except statement.
This exercise limited you to four operators, but you can add additional operators, as in:
Additionally, you may want to rewrite part of the program with a loop statement.
There are many ways to handle errors and modify and improve each and every coding project. It is important to keep in mind that there is no single correct way to solve a problem that we are presented with.
Conclusion
This tutorial walked through one possible approach to building a calculator on the command line. After completing this tutorial, you’ll be able to modify and improve the code and work on other projects that require user input on the command line.
We are interested in seeing your solutions to this basic command-line calculator project! Please feel free to post your calculator projects in the comments.
Next, you may want to create a text-based game like tic-tac-toe or rock-paper-scissors.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
d3174 / Калькулятор Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| print ('Приветствуем вас в калькуляторе Python') |
| q1 = int (input('Введите число 1: ')) |
| q2 = int (input('Введите число 2: ')) |
| v = int (input('Какую операцию вы хотите выполнить? \n 1 Сложение \n 2 Вычитание \n 3 Деление \n 4 Умножение \n')) |
| if v == 1: |
| r = q1 + q2 |
| p = 'сложения' |
| t = p |
| if v == 2: |
| r = q1 — q2 |
| l = 'вычитания' |
| t = l |
| if v == 3: |
| r = float(q1 / q2) |
| m = 'деления' |
| t = m |
| if v == 4: |
| r = q1 * q2 |
| n = 'умножения' |
| t = n |
| print ('Результат ',t,' = ',r) |
yasich7 commented May 5, 2019
Where I can teach a Python?
MotoIlyuha commented Jan 11, 2021
MotoIlyuha commented Jan 11, 2021
Очень рекомендую курс на платформе Stepik (https://stepik.org/course/512/syllabus). Я сам выучил базовый уровень языка по этому курсу всего за две недели, что в дальнейшем помогло мне выигрывать серьезные олимпиады. Звучит как реклама 🙂
SergMagpie commented Jan 28, 2021
Очень рекомендую курс на платформе Stepik (https://stepik.org/course/512/syllabus). Я сам выучил базовый уровень языка по этому курсу всего за две недели, что в дальнейшем помогло мне выигрывать серьезные олимпиады. Звучит как реклама 🙂
Its great! I’m too learn in Stepik
SmIrOn123 commented Sep 11, 2021
`print (‘Приветствуем вас в калькуляторе Python’)
q1 = int (input(‘Введите число 1: ‘))
q2 = int (input(‘Введите число 2: ‘))
q3
if q3== +:
r = q1 + q2
p = ‘сложения’
t = p
if q3 == -:
r = q1 — q2
l = ‘вычитания’
t = l
if q3 == *:
r = float(q1 / q2)
m = ‘деления’
t = m
if q3 == /:
r = q1 * q2
n = ‘умножения’
t = n
print (‘Результат ‘,t,’ = ‘,r)`
syrgabek commented Mar 3, 2022
tenz0wo commented Apr 14, 2022 •
еще продуктивнее)
f = int(input(‘Выберите функцию \nСложение — 1\nВычитание — 2\nУмножение — 3\nДеление — 4\nВозведение в квадрат — 5\nВычисление квадратного корня — 6\nВычисление синуса — 7\nВычисление косинуса — 8\n’))
if f == 1:
ch1 = int(input(‘Введите первое число: ‘))
ch2 = int(input(‘Введите второе число: ‘))
r = ch1 + ch2
elif f == 2:
ch1 = int(input(‘Введите первое число: ‘))
ch2 = int(input(‘Введите второе число: ‘))
r = ch1 — ch2
elif f == 3:
ch1 = int(input(‘Введите первое число: ‘))
ch2 = int(input(‘Введите второе число: ‘))
r = ch1 * ch2
elif f == 4:
ch1 = int(input(‘Введите первое число: ‘))
ch2 = int(input(‘Введите второе число: ‘))
r = float(ch1 / ch2)
elif f == 5:
ch = int(input(‘Введите число: ‘))
r = ch * ch
elif f == 6:
ch = int(input(‘Введите число: ‘))
sqrt = ch ** (0.5)
r = sqrt
elif f == 7:
ch = int(input(‘Введите число: ‘))
r = math.sin(ch)
elif f == 8:
ch = int(input(‘Введите число: ‘))
r = math.cos(ch)
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.