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

Z M*_*onk 1 python python-3.x

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

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

  File "p22.py", line 24
    cat = [+,-,*]
            ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

如果我确实放置引号,那么我似乎丢失了运算符的函数,如下例所示:

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

这是完整的代码:

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()
Run Code Online (Sandbox Code Playgroud)

idj*_*jaw 16

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

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')
Run Code Online (Sandbox Code Playgroud)

要在此行上提供额外的信息:

operations[op](num1, num2)
Run Code Online (Sandbox Code Playgroud)

operations是一个字典,我们使用[]字典上的值来访问该值,方法是将输入op的密钥作为密钥传递给该字典.有了这个,你现在掌握了方法,只需要通过传递参数(,)来调用它. num1num2

  • 而`operations [op](num1,num2)`来获得一个有用的错误 (2认同)