python - 在 Python 3 中将运算符放在列表中

标签 python python-3.x

我想将运算符作为列表放置,然后从列表中调用一个元素作为运算符使用。

如果我没有在运算符周围放置引号,那么我会收到列表内逗号的语法错误:

  File "p22.py", line 24
    cat = [+,-,*]
            ^
SyntaxError: invalid syntax

如果我确实放置了引号,那么我似乎失去了运算符的功能,如本例所示:

  File "p22.py", line 30
    a = (x which y)
               ^
SyntaxError: invalid syntax

完整代码如下:

import random

def start():
    print('\n________________________________________')
    print('|                                      |')
    print('|         Zach\'s Tutorifier!          |')
    print('|                                      |')
    print('|                                      |')
    print('|     Instructions:                    |')
    print('| Select the type of math you want     |')
    print('| to practice with:                    |')
    print('| 1-Add 2-Subtract 3-Multiply          |')
    print('|--------------------------------------|')
start()
math = int(input('> ')) - 1
cat = ['+','-','*']

def problems():
    which = cat[math]
    x = random.randint(0,9)
    y = random.randint(0,9)
    a = (x which y)
    print('What is %i %s %i?' % (x, which, y) )
    answer = input('> ')
    if answer == a:
        print('Congratulations! Try again? (Y/N)')
        again = input('> ')
        if again == 'Y' or again == 'y':
            problems()
        else:
            start()
    else: 
        print('Try again!')
problems()

最佳答案

为了正确翻译数学的字符串表示形式 operator ,您实际上可以使用内置的 operator 模块为您完成此操作。简单地说,将您的字符串运算符映射到方法调用,并相应地工作。这是一个示例,您应该能够弄清楚如何应用到您的代码中:

from operator import add, sub, mul

operations = {'+': add, '-': sub, '*': mul}

op = input("enter +, - or *")
num1 = int(input("enter a number"))
num2 = int(input("enter another number"))

expected_result = int(input("what do you think the answer should be"))

result = operations[op](num1, num2)

if expected_result == result:
    print('you are right')
else:
    print('no, you are wrong')

在此行提供额外的信息:

operations[op](num1, num2)

operations 是一个字典,我们通过将输入的 op 作为那本词典的关键。有了这个,您现在有了方法,只需通过传递参数(num1num2)调用它。

关于python - 在 Python 3 中将运算符放在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712440/

相关文章:

python - 删除空条目并将它们添加为列表的前一个条目中的空格

python - (VS 代码)Pylint 在导入模块时抛出语法错误,但在我运行代码时工作正常

Python 3 运算符.div?

python - Pyglet无法加载.wav文件

python - Python 类和子类

python - 为什么找不到子字符串时 Python 会抛出错误?

python - 导入的模块不正确

python - SQLAlchemy 可以仅使用 MySQL 的 SSCursor 进行某些查询吗?

python - 如何显示 Pandas 数据框的子集?

python-3.x - 将应用程序部署到 Heroku 时的 "ERROR: No matching distribution found for numpy"