用Python编写的计算器脚本只打印输入的数字,不执行操作

0 投票
1 回答
2182 浏览
提问于 2025-04-18 07:46

我正在用Python写一个计算器脚本,这个脚本会让用户输入两个数字,然后根据用户选择的数学运算(比如加法、减法等)来计算结果。但是,当我在PyCharm这个开发环境中运行脚本时,它并没有进行计算,而是直接输出了这两个数字。举个例子,如果我输入的数字是“2”和“7”,选择的运算是“乘法”,我期待的结果应该是“14”,但实际输出却是“27”。

我使用的是Python 3.4.0版本,正如上面提到的,我的开发环境是PyCharm。

以下是我脚本的全部代码:

from math import sqrt

greeting = "Welcome to calculator!"
print(greeting)
loop = 0

#Defines methods for mathematical operations: add, subtract etc.
def add(num1, num2):
    ans = num1 + num2
    return ans


def subtract(num1, num2):
    ans = num1 - num2
    return ans


def multiply(num1, num2):
    ans = num1 * num2
    return ans


def divide(num1, num2):
    ans = num1 / num2
    return ans


def exponent(num1, num2):
    ans = num1 ** num2
    return ans


def square_root(num1):
    ans = sqrt(num1)
    return ans


def get_num():
    num = input("Enter a number: ")
    if num == "ans":
        num = ans
        return ans
    else:
        return num

#Gets input from the user, executes the appropriate operation and prints the answer
while loop == 0:
    operation = input("Enter an operation: ")
    if operation == "add" or "+":
        num1 = get_num()
        num2 = get_num()
        ans = add(num1, num2)
        print(ans)

    elif operation == "subtract":
        num1 = get_num()
        num2 = get_num()
        ans = subtract(num1, num2)
        print(ans)

    elif operation == "multiply":
        num1 = get_num()
        num2 = get_num()
        ans = multiply(num1, num2)
        print(ans)

    elif operation == "divide":
        num1 = get_num()
        num2 = get_num()
        ans = divide(num1, num2)
        print(ans)

    elif operation == "exponent":
        num1 = get_num()
        num2 = get_num()
        ans = exponent(num1, num2)
        print(ans)

    elif operation == "square root":
        num1 = get_num()
        square_root(num1)

    else:
        print("Operation not recognized.")

1 个回答

3

目前你的第一个 if 语句(加法)正在被评估,应该是:

operation == "add" or operation == "+":

或者正如保罗指出的:

operation in ('add','+'):

这也可以工作。

or 是用来连接两个表达式,并检查它们是否为真。只有某些特定的值被认为是假的,而“+”并不在其中。一旦这样做后,你的 num1num2 就变成了字符串……“2” + “7” 会被连接成 “27”。

这一行:

num = input("Enter a number: ")

应该将 num 转换为整数:

num = int(input("Enter a number: "))

撰写回答