Python:我的初学者计算器有一个小错误

时间:2013-04-23 11:10:39

标签: python python-3.x calculator

我刚刚开始使用python,而且我不太了解问题所在。我有这个计算器代码,我试图从头开始创建,但是我遇到了一个小问题。

def Addition():
    print('Addition: What are your numbers?')
    a = int(input('First Number:'))
    b = int(input('Second Number:'))
    print('Your Answer is:', a + b)


def Subtraction():
    print('Subtraction: What are your numbers?')
    c = int(input('First Number:'))
    d = int(input('Second Number:'))
    print('Your Answer is:', c - d)


def Multiplication():
    print('Multiplication: What are your numbers?')
    e = int(input('First Number:'))
    f = int(input('Second Number:'))
    print('Your Answer is:', e * f)


def Division():
    print('Division: What are your numbers?')
    g = int(input('First Number:'))
    h = int(input('Second Number:'))
    print('Your Answer is:', g / h)

x = 'test'


def Question():
        x = input('What would you like to do? (Add, Subtract, Divide, Multiply or         Quit)')
        while x == 'Add' or 'add' or 'A' or 'a':
            x = 'test123'
            print(Addition())
            x = 'test'
        while x == 'Divide' or 'Div' or 'D' or 'divide' or 'div':
            x = 'test'
            print(Division())
            x = 'test'
        while x == 'Multiply' or 'Mul' or 'Mult' or 'multiply' or 'mult' or 'Times' or 'times':
            x = 'test'
            print(Multiplication())
            x = 'test'
        while x == 'Subtract' or 'Take Away' or 'Take away' or 'take Away' or 'take away':
            x = 'test'
            print(Subtraction())
            x = 'test'
        while x == 'Quit' or 'exit' or 'quit' or 'Exit':
            x = 'test'
            print(exit())
        while x == 'test':
            print(Question())


while x == 'test':
        print(Question())

当我运行代码时,无论输入是什么,它都会在询问我问题之后决定Addition()是它想要运行的。这是因为我先定义了它,还是出于其他原因?另外,我不想使用任何elses代码,但是有更简单的方法吗?非常感谢任何帮助!

谢谢大家的帮助!

3 个答案:

答案 0 :(得分:3)

您的代码存在多处问题,但始终执行Addition函数的原因是因为比较字符串并不像您认为的那样工作。当你写

while x == 'Add' or 'add' or 'A' or 'a':

这被解释为

while (x == 'Add') or 'add' or 'A' or 'a':

因此检查x是否等于'Add'或任何字符串文字评估为'True',他们这样做。编写比较的更好方法是使用in运算符(并使用if语句而不是一段时间):

if x.lower() in ["add", "a"]:

在字符串上调用lower会将其转换为所有小写字符,因此将其与“添加”进行比较就足够了,您无需将其与任何其他只是大小写不同的拼写进行比较。

另外需要注意的是,在代码中有大量不必要的重复 - 您可以将输入部分重构为单独的函数,而不是将代码复制四次:

def getInput():
    a = int(input('First Number:'))
    b = int(input('Second Number:'))
    return a, b

您现在可以编写如下函数:

def addition():
    print('Addition: What are your numbers?')
    a, b = getInput()
    print('Your Answer is:', a + b)

或者您可以通过创建一个通用评估函数来进一步简化这一过程,该函数将函数作为应用于输入值的Argument:

def evaluate(name, function):
    print("%s: What are your numbers?" % name)
    a, b = getInput()
    print("Your Answer is:", function(a, b))

这允许您根据'evaluate'函数定义加法,乘法等,并将lambda作为参数传递:

evaluate("Addition", lambda x, y: x + y)
evaluate("Multiplication", lambda x, y: x * y)
evaluate("Two times a to the power of b", lambda x, y: 2 * (x ** y))

答案 1 :(得分:3)

问题在于这一行:

    while x == 'Add' or 'add' or 'A' or 'a':

应该是:

    if x in ['Add', 'add', 'A', 'a']:

然后再做其他人的陈述。

答案 2 :(得分:1)

我认为你需要阅读有关函数和函数参数的内容。还要看看循环及其用法。

以下是您的代码的重构版本。它并不完美,但它应该让你知道在哪里移动。

def addition(a, b):
    return a + b


def subtraction(a, b):
    return a - b


def multiplication(a, b):
    return a * b


def division(a, b):
    if b != 0:
        return a / b
    else:
        print("Error: division by zero")


def question():
        x = input('What would you like to do? (Add, Subtract, Divide, Multiply or Quit)')
        while x != "Quit":
            a = int(input("Enter number a: "))
            b = int(input("Enter number b: "))

            if x == "Add":
                print(addition(a,b))
            elif x == "Subtract":
                print(subtraction(a,b))
            elif x == "Divide":
                print(division(a,b))
            elif x == "Multiply":
                print(multiplication(a,b))
            else:
                print("Wrong operation")

            x = input('What would you like to do? (Add, Subtract, Divide, Multiply or Quit)')

if __name__ == "__main__":
    question()

以下是运行后如何使用它:

What would you like to do? (Add, Subtract, Divide, Multiply or Quit)"Add"
Enter number a: 4
Enter number b: 5
9
What would you like to do? (Add, Subtract, Divide, Multiply or Quit)"Subtract"
Enter number a: 6
Enter number b: 3
3
What would you like to do? (Add, Subtract, Divide, Multiply or Quit)"Quit"