在两个数字之间实现输入运算符

Implementing inputted operator in between two numbers

我最近一直在搞进口海龟和三角函数:

turtle.goto((x/math.pi)*wavelength,(ypos/10)+math.sin(x)*amplitude)

(这只是我的代码片段,与x位置无关。)

(ypos/10)+math.sin(x)*amplitude

可以很容易地重新整形为标准公式:

y = b + mx (*z for amplitude)

我想知道的是,如何将运算符输入到变量中,然后用不同的符号代替加法或乘法?我已经尝试了所有我能想出的办法。

编辑:这些运算符是任何特定的数据类型吗?我也找不到任何相关信息。

how could i input an operator into a variable and replace the addition or multiplication with a different symbol?

我建议您探索 Python 的 operator.py 模块。这是一个简单的例子,只显示了四个基本的计算器操作:

import operator
from random import randint

operations = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
}

a, b = randint(0, 100), randint(0, 100)

while True:

    operation = input("Enter an operation (+, -, * , / or 'quit') ")

    if operation in operations:

        c = operations[operation](a, b)

        print("{} {} {} = {}".format(a, operation, b, c))
    elif operation == 'quit':
        break
    else:
        print("try again")

你不应该做的是考虑eval。您不应该只对任何东西开放您的代码,而应该对一些合理且安全的预定义操作集开放。

用法

> python3 test.py
Enter an operation (+, -, * or /) +
25 + 97 = 122
Enter an operation (+, -, * or /) -
25 - 97 = -72
Enter an operation (+, -, * or /) *
25 * 97 = 2425
Enter an operation (+, -, * or /) /
25 / 97 = 0.25773195876288657
Enter an operation (+, -, * or /) quit
>