如何验证计算器程序的整数运算符



我正在尝试创建一个程序,允许用户输入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()

您应该检查用户输入的操作是否有效,tryexcept在此不起作用,因为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

您应该使用python的内置operator模块。然后你可以使用这样的dict:

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

这样,您就不需要自己实现简单的运算符功能。

最简单、最干净的方法是在Python中使用operator模块,因此userOutput方法如下所示。不过,您应该对代码进行一些更改,将houroperator变量重命名为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)

相关内容

  • 没有找到相关文章

最新更新