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», тоже очень полезна новичкам.
Консольный калькулятор на Python:
Как говорилось выше, мы сделаем легкий калькулятор на Python, и для этого нам нужно создать только один Python файл, я его назову «main.py».
Внутри него создадим функцию которая будет за всё отвечать, вот примерно так:
То есть мы создаём функцию где происходит вся логика, внутри неё первым делом выводим сообщение, что мы открыли калькулятор.
Потом запускаем бесконечный цикл и в нём даём выбрать действие, тут как обычно, то есть, если выбираем знак плюса, то будем складывать и т.д..
После идёт проверка команд, если выбрать кнопку «q», то выходим из программы, если же это арифметический знак, то вводим два числа, кладём их в переменные в формате числа с плавающей точкой.
Потом проверяем конкретный знак, зависимо от него и делаем действии, выводим на экран, самое интересное это с делением, мы делаем проверку, если делитель, то есть «y», равен нулю то тогда не будем делить.
Последние что осталось это объявить переменную, вот: