使用Python程序的基本计算器程序

在本教程中,我们将使用Python构建一个基本的计算器。我想大家都对基本计算器有所了解。我们将为用户提供六个选项,从中选择一个选项,然后执行相应的操作。以下是我们将要执行的算术运算。

  • 加成

  • 减法

  • 乘法

  • 楼层部

  • 模数

尝试自行实现。请按照以下步骤为一个简单的计算器编写代码。

算法

1. Initialise the two numbers.
2. Ask the user to enter an option by giving six options.
3. After getting the option from the user write if conditions for every operation based on the option.
4. Perform the respective operation.
5. Print the result.

让我们编写代码。

示例

## initializing the numbers
a, b = 15, 2
## displaying catalog for the user choice
print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo")
## getting option from the user
option = int(input("Enter one option from the above list:- "))
## writing condition to perform respective operation
if option == 1:
   print(f"Addition: {a + b}")
elif option == 2:
   print(f"Substraction: {a - b}")
elif option == 3:
   print(f"Multiplication: {a * b}")
elif option == 4:
   print(f"Division: {a / b}")
elif option == 5:
   print(f"Floor Division: {a // b}")
elif option == 6:
   print(f"Modulo: {a % b}")

输出结果

如果运行上述程序,将得到以下输出。

1 - Addition
2 - Substraction
3 - Multiplication
4 - Division
5 - Floor Division
6 - Modulo
Enter one option from the above list:- 3
Multiplication: 30

让我们再次执行程序

示例

## initializing the numbers
a, b = 15, 2
## displaying catalog for the user choice
print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo")
## getting option from the user
option = int(input("Enter one option from the above list:- "))
## writing condition to perform respective operation
if option == 1:
   print(f"Addition: {a + b}")
elif option == 2:
   print(f"Substraction: {a - b}")
elif option == 3:
   print(f"Multiplication: {a * b}")
elif option == 4:
   print(f"Division: {a / b}")
elif option == 5:
   print(f"Floor Division: {a // b}")
elif option == 6:
   print(f"Modulo: {a % b}")

输出结果

如果运行上述程序,将得到以下输出。

1 - Addition
2 - Substraction
3 - Multiplication
4 - Division
5 - Floor Division
6 - Modulo
Enter one option from the above list:- 6
Modulo: 1

结论