Как сделать бесконечный калькулятор в python
Перейти к содержимому

Как сделать бесконечный калькулятор в python

  • автор:

Как в Python зациклить код так что он возвращался к изначальному вопросу?

print (Back.RED)
while True:
if what == «+»:
r = a + b
print(«результат: » + str(r))
elif what == «-«:
r = a — b
print(«результат: » + str(r))
else:
print(«Не та опирация»)
break
62511e88bc913250147764.png

Я нолик в петоне ,не понимаю как с помощью вайл зациклить сам вопрос , чтобы после ответа ,можно было снова проводить операции с числами не закрывая exe файл и перезапуская его.

Как зациклить калькулятор и при нажатии X он переставал работать?

Kromster's user avatar

тоже самое, что и у ответа ранее, но с адаптацией к версии 3.8:

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.8.43486

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Calculator Program in Python using while loop [New]

We will create a calculator program in python using while loop and functions. It is also called menu driven calculator program.

Menu-driven calculator program: According to the input, it will perform addition, subtraction, multiplication, and division of two numbers.

Calculator Program in Python using while loop

We will make a calculator by creating a menu-driven program in python for addition, subtraction, multiplication, and division of two numbers. The user will choose any options, and then we will take input from the user and call the appropriate function. We will perform some operations and print the result.

Calculator Program in Python using while loop

1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit Enter your choice(1-5):1
Enter 1st Number:2
Enter 2nd Number:6
Addition= 8

Video Solution

Quick algorithm for Calculator Program:

  • Print the menu for those arithmetic operations our program can perform, i.e., addition, subtraction, multiplication, and division.
  • Take the input from the user.
  • According to their choice, call the appropriate function.
  • Handle edge case for division operation, i.e., denominator can’t be equal to zero.
  • We will perform the arithmetic operation and print the result.

Python Program for Calculator using functions

In this program, I made a calculator using functions, a dictionary and a while loop.

  • functions: To perform different arithmetic operations like addition, subtraction, multiplication and division.
  • dictionary: To assign every arithmetic symbol to the function name. [‘+’ to add function]
  • while loop: To perform repetitive calculations according to user choice.
  • Users can also continue calculations with the previous answers or can also perform the new calculation.

About this Menu-driven Calculator Program:

We made a simple calculator program in python using a while loop, if-else statements, and functions. According to the user’s choice, this program can add, subtract, multiply and divide two numbers. It is also a menu-driven program to perform arithmetic operations in python.

Creating an Advanced Calculator with Python.

Christopher Quiles

This lab will show you how to create advanced calculators using Python.

This is my first Python project and have found this to be great place to start to grasp the fundamentals of using the Python’s programming language. This project will give us practice on getting input and numbers from users instead of strings.

There are many ways of creating a calculator in Python, and we’ll explore a few of them today. We’ll be using math operators, variables, conditional statements, functions, and handle user input to make our calculators.

Install Python:
It is recommended that you should have Python 3 installed. If you still need to install it, click on the bold link to follow the appropriate steps for to install python for your operating system.

Create a working directory:
After installing Python, create a working directory from your CLI so you can create your files to put this project in. You can name this folder whatever you feel comfortable with. For example I’ve named mine CODE.

Basic Calculator:

First off let’s create a file for the code. For example you can name this basic.py file name if you’d like as the example shows below.

Basically, what we are going to do here is create a simple calculator. We are going to get two numbers form the user and print those numbers to the screen. In this script we are asking to convert the string into numbers. A string in Python is a sequence of characters. This basic calculator will use (int) to convert what is in our parenthesis into integers which are also known as (whole numbers). However, it will not calculate decimals.

Notice how we use float(s) instead of integers here. Float (floating point real values) − represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats let use calculate decimals, and of course whole numbers.

To run a python script enter ($ python xxxx.py). Then enter the numbers you want to add and subtract.

Here is a link to the working code of our basic calculator.

Advanced Calculator:

Let’s build a more advanced calculator. Our last calculator was fine, except it could only do addition. The main thing we are going to be adding to this script is the operator, which will recognize addition, subtraction, multiplication, and division. Also, we will be adding if and elif statements to our script.

“If statements are logical blocks used within programming. They’re conditional statements that tell a computer what to do with certain information.… So, if statements essentially mean: ‘If something is true, then do something, otherwise do something else.”

“In programming languages, an else statement is an alternative statement that is executed if the result of a previous test condition evaluates to false.”

To run a python script enter ($ python xxxx.py).

We also used an “else” statement to report an invalid operator is something other than addition, subtraction, multiplication, or division is used.

Here is a link to the working code of our Advanced Calculator.

Eval () Calculator:

Eval is an alternation calculator available and is much less code than our advanced calculator. “ eval allows any string to be evaluated as a Python expression. It can accept arbitrary expressions (e.g. 1+2-3*4 ) not just binary operations. However, it should be used with caution in production environments because it can be used for malicious purposes.

To run a python script enter ($ python xxxx.py).

Here is a link to the working code for the Eval Calculator.

Conclusion:

Like I mentioned in the beginning, there are many ways to create a calculator in Python these are just a few. Hopefully you found this project useful and gave you some beginner level experience with Python. I recommend saving these calculators for future projects and even improving them in the future. Thanks for the taking the time!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *