简体   繁体   English

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

[英]How to validate operators with integers for a calculator program?

I'm trying to create a program that allows the user to input one of 4 operators (addition, subtraction, multiplication, or division) and then two numbers. 我正在尝试创建一个程序,该程序允许用户输入4个运算符之一(加,减,乘或除),然后输入两个数字。 The program then calculates the operation. 然后,程序将计算操作。 I can't seem to validate the operators for the output, though. 我似乎无法验证输出的运算符。 I'm trying with an if ... else statement now, but no luck. 我正在尝试使用if ... else语句,但是没有运气。 Any pointers here? 这里有指针吗?

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

You should check if user entered valid operation, try except wont work here since input() won't throw any errors. 您应该检查用户是否输入了有效的操作,请try except此处except操作,因为input()不会引发任何错误。 Also here's more elegant way to get 2 valid integers from user, and calculate final equation (using eval() ) 另外,这是从用户那里获得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))

Output: 输出:

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

You should use the builtin operator module of python. 您应该使用python的内置operator 模块 Then you can use a dict like this: 然后,您可以使用这样的字典:

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

This way you don't need to implement simple operator functionality yourself. 这样,您无需自己实现简单的操作员功能。

The easiest and cleanest way to do so, is to use the operator module in Python, so your userOutput method would become as follows. 最简单,最干净的方法是在Python中使用operator模块,因此userOutput方法将如下所示。 A few changes you should do on your code, though, would be to rename hour operator variable to op , as it would conflict with python module name, and update the operator as a return from the userInput() : 但是,您应该对代码进行一些更改,将小时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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM