python - 制作一个接受用户输入的计算器,直到用户输入 0 但无法正常工作
问题描述
我是python的新手,正在尝试制作计算器,但不知道如何制作我正在制作一个计算器,它将接受用户的输入,直到用户输入0然后执行操作,但如果有人可以帮忙,我会被困在这里我做这项工作我会非常感谢他/她。
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
解决方案
这是使用itertools.reduce
. 不要重复相同的代码来多次输入一个数字,而是将其放入一个函数中。这也将有助于避免代码中的错误并阐明逻辑。第二个生成器函数可用于获取一系列值,直到用户输入零。
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
推荐阅读
- matlab - 在 cmd 上运行 MATLAB 脚本,无需打开 GUI 窗口或图标
- docker - People are connecting through my private network
- node.js - 在 node.js 服务器上存储 mp4 文件的位置?
- java - 我似乎为我的简单计数器程序做的一切都是正确的,但是当我在命令行上运行程序时没有任何反应
- java - 从 RestFB 的帖子中获取用户 ID 评论
- google-cloud-functions - Would it be possible that we have one Google Cloud function listen to multiple topics?
- c++ - Vector of derived class objects using shared_ptr
- python - 无法调用 canvas.show()
- python - 如何循环回到程序的开头?Python
- python - 为什么多个 on_message 事件不起作用?