Skip to main content
 首页 » 编程设计

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

2025年05月04日8lyhabc

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

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

  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 作为那本词典的关键。有了这个,您现在有了方法,只需通过传递参数(num1、num2)调用它。