首页 > 解决方案 > 制作一个接受用户输入的计算器,直到用户输入 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")

标签: pythonpython-3.xpython-2.7calculator

解决方案


这是使用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))
    

推荐阅读