我想将操作员作为列表,然后从列表中调用元素作为操作员。
如果我不在操作员周围放置报价,那么我会收到列表中逗号的语法错误:
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()
为了正确地翻译 数学操作员的字符串表示,您实际上可以使用indentIn ocerator 模块来执行此操作你。简而言之,将字符串运算符映射到方法调用,然后相应地工作。这是一个示例,您应该能够弄清楚如何应用于您的代码:
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
(来 call 。
可以使用Altough eval
,他们说的是正确的:除非它是严格的必要条件,否则您没有其他选择,并且您没有最大的安全性。好吧,只是不要使用它,尽管它们需要更多代码,但有多种方法可以做到这一点。
我的主张正在映射操作员:
import random
# NEW CODE
def sum(a, b):
return a + b;
def substract(a, b):
return a - b;
def multiply(a, b):
return a * b;
# END OF NEW CODE
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 = {
"+": sum,
"-": substract,
"*": multiply
}
def problems():
# NEW CODE
operator_char= cat.keys()[math]
operation = cat[math]
# END OF NEW CODE
x = random.randint(0,9)
y = random.randint(0,9)
print('What is %i %s %i?' % (x, operator_char, y) )
answer = input('> ')
# NEW CODE
if answer == operation(x, y):
# END OF NEW CODE
print('Congratulations! Try again? (Y/N)')
again = input('> ')
if again == 'Y' or again == 'y':
problems()
else:
start()
else:
print('Try again!')
problems()