如何为计算器程序使用整数验证运算符?

时间:2018-12-08 19:32:38

标签: python arrays loops validation

我正在尝试创建一个程序,该程序允许用户输入4个运算符之一(加,减,乘或除),然后输入两个数字。然后,程序将计算操作。我似乎无法验证输出的运算符。我正在尝试使用if ... else语句,但是没有运气。这里有指针吗?

operator = ""
numbers = []
inputNumbers = ["first number", "second number"]

def userInput():
    try:
        operator = input("Please choose a valid operation (+, -, *, /): ")
    except:
        print("Please enter a valid operator.")
    for inputNumber in inputNumbers:
        user_num_input = -1
        while user_num_input < 0:
            try:
                user_num_input = int(input("Type in {}: ".format(inputNumber)))
            except:
                user_num_input = -1
                print("Please enter a whole number.")
            if user_num_input > -1:
                numbers.append(user_num_input)
userInput()

def addNumbers():
    add = numbers[0] + numbers[1]
    return add(numbers)

def subNumbers():
    sub = numbers[0] - numbers[1]
    return sub(numbers)

def mulNumbers():
    mul = numbers[0] * numbers[1]
    return mul(numbers)

def divNumbers():
    div = numbers[0] / numbers[1]
    return div(numbers)

def userOutput():
    if operator == "+":
        print(numbers[0], "+", numbers[1], "=", addNumbers())
    elif operator == "-":
        print(numbers[0], "-", numbers[1], "=", subNumbers())
    elif operator == "*":
        print(numbers[0], "*", numbers[1], "=", mulNumbers())
    elif operator == "/":
        print(numbers[0], "/", numbers[1], "=", divNumbers())
userOutput()

3 个答案:

答案 0 :(得分:1)

您应检查用户是否输入了有效的操作,try不会引发任何错误,因此except input()在这里将无法工作。另外,这是从用户那里获得2个有效整数并计算最终方程式(使用eval())的更优雅的方法

inputNumbers = ["first number", "second number"]
operations = ['+', '-', '*', '/']

numbers = []
operator = ''

while not operator:
    operator = input('Please choose a valid operation (+, -, *, /): ')
    if operator not in operations:
        print("Please enter a valid operator.")

while len(numbers) < len(inputNumbers):
    try:
        numbers.append(int(input("Type in {}: ".format(inputNumbers[len(numbers)]))))
    except:
        print("Please enter a whole number.")

result = eval(operator.join(map(str, numbers)))
print('{} {} {} = {}'.format(numbers[0], operator, numbers[1], result))

输出:

Please choose a valid operation (+, -, *, /): addition
Please enter a valid operator.
Please choose a valid operation (+, -, *, /): /
Type in first number: 123.321
Please enter a whole number.
Type in first number: 10 
Type in second number: hundred
Please enter a whole number.
Type in second number: 100
10 / 100 = 0.1

答案 1 :(得分:1)

您应该使用内置的python operator module。然后您可以使用这样的字典:

import operator

operator_dict = {"+": operator.add, 
                 "-": operator.sub, 
                 "*": operator.mul,
                 "/": operator.truediv}
user_input = input("Please choose a valid operation (+, -, *, /): ")
operator_func = operator_dict.get(user_input, None)
# if operator_func is not None then the input was correct!
if operator_func is not None:
    ... get the numbers ...
    print("{}{}{}={}".format(num1, user_input, num2, operator_func(num1, num2))

这样,您无需自己实现简单的操作员功能。

答案 2 :(得分:0)

最简单,最干净的方法是在Python中使用operator模块,因此您的userOutput方法将如下所示。 不过,您应该对代码做一些更改,将小时operator变量重命名为op,因为它会与python模块名称冲突,并更新operator作为返回值来自userInput()

import operator
op = ""
numbers = []
inputNumbers = ["first number", "second number"]
operators = {
        '+' : operator.add,
        '-' : operator.sub,
        '*' : operator.mul,
        '/' : operator.truediv,
        '%' : operator.mod,
        '^' : operator.xor,
}

def userInput(op):
    while not op:
        op = input("Please choose a valid operation (+, -, *, /): ")
        if op not in operators:
            print("Please enter a valid operator.")
            op = ""
    for inputNumber in inputNumbers:
        user_num_input = -1
        while user_num_input < 0:
            try:
                user_num_input = int(input("Type in {}: ".format(inputNumber)))
            except:
                user_num_input = -1
                print("Please enter a whole number.")
            if user_num_input > -1:
                numbers.append(user_num_input)
    return op

def userOutput(op, operators):
    result = operators[op](numbers[0], numbers[1])
    print("{} {} {} = {}". format(numbers[0], op, numbers[1], result))

op = userInput(op)
userOutput(op, operators)