制作一个计算器,它从用户那里获取输入,直到用户输入 0 但无法正常工作

Making a Calculator which take input from user until user enter 0 but not working correctly

我是 python 的新手,正在尝试制作计算器,但不知道如何制作 我正在制作一个计算器,它将接受用户的输入,直到用户输入 0,然后进行操作 但我被困在这里 如果有人可以帮助我完成这项工作,我将非常感谢 him/her。

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")

减法的问题是变量total没有初始化。

乘除法的问题在于,当用户输入“0”时,变量total在while语句中被检查之前被乘以或除以零。我通常会这样做:

elif options == 3:
total = 1
while True:
    try:
        num = float(input("(Enter '0' When Complete.) Enter Number "))  # No need to escape single quotes when your string uses double quotes 
        if num == 0:
            break
    except ValueError:
        print("Error, Enter Valid Number")
        continue
    total = total * num
print("Your Calculated Value is: {}".format(total))

但是,如果您想快速修复,可以让用户输入 1 而不是 0 进行乘法和除法:

elif options == 4:
total = 1
while (num != 1): 
    try:
        num = float(input("(Enter '1' When Complete.) Enter Number "))
    except:
        print("Error, Enter Valid Number")
        continue
    total = total / num
print("Your Calculated Value is: {}".format(total))

编辑:如果你希望除法按照你指定的方式工作,你可以这样做:

elif options == 2:
    total = 1
    try:
        first_number = float(input("(Enter '0' When Complete.) Enter Number "))
        if first_number == 0:
            print("Your Calculated Value is: 0")
            exit()
    except ValueError:
        print("Error, Enter Valid Number")
        continue

    total = 1
    while True:
        try:
            num = float(input("(Enter '0' When Complete.) Enter Number "))
            if num == 0:
                break
        except ValueError:
            print("Error, Enter Valid Number")
            continue
        total = total * num
    print("Your Calculated Value is: {}".format(total + first_number))

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

而不是

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

use(变化仅在 2nd 行和 last一)

elif options == 2:
    total = None
    while (num != 0):
        try:
            num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
        except:
            print("Error, Enter Valid Number")
            continue
        total = total - num if total is not None else num

您可以对 elif options == 4: 分支使用相同的方法。