0

I've just started with python and I'm not too great at learning where the problems lie. I have this calculator code which I am trying to create from scratch, however I've run into a small problem.

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

When i run the code it decides that Addition() is what it wants to run after asking me the question, no matter the input. Is this because I have defined it first, or for some other reason? Also, I don't want to use anyone elses code, but is there a simpler way to do this? Any help is greatly appreciated!

Thank you everyone for the help!

4

3 回答 3

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语句而不是 while):

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

调用lowerString 会将其转换为所有小写字符,因此将其与 'add' 进行比较就足够了,您无需将其与任何其他大小写不同的拼写进行比较。

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

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)

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

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

这允许您根据“评估”函数定义加法、乘法等,将 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))
于 2013-04-23T11:16:13.703 回答
3

问题是这一行:

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

应该是:

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

然后做出其他的 elif 语句。

于 2013-04-23T11:16:34.163 回答
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"
于 2013-04-23T11:27:48.823 回答