使用 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
结论
如果你对本教程有任何疑问,请在评论部分提出。
广告