关于简单数学程序的Python无效语法

时间:2015-11-03 19:08:09

标签: python python-2.7 syntax

我正在尝试创建随机数学问题测验,但冒号出现为无效语法。是由于操作员我不能使用冒号?如果我把它拿出来,它也被视为无效的语法。

这是创建'correct_answer'变量的代码,因此如果推文答案中的用户正确或不正确,则让他们知道。如果需要整个代码(我确定它不会是因为这可能是我真的很蠢)我可以发布它。

if operator==+:
    correct_answer=random_number1+number2
elif operator==-:
    correct_answer=random_number1-number2
else:
    correct_answer=random_number1*number2

完整代码:

import random

name=raw_input("Hi what's your name?")
print "Alrighty lets go, "+name+"!"

for i in range(10):
    operator_list=('+','-','x')
    operator=random.choice(operator_list)
    random_number1=random.randint(1,12)
    random_number2=random.randint(1,10)

question=1
print random_number1, operator, random_number2

if operator==+:
    correct_answer=random_number1+number2
elif operator==-:
    correct_answer=random_number1-number2
else:
    correct_answer=random_number1*number2


answer = eval(str(int(raw_input("What is the answer?"))))


if answer==correct_answer:
    print "Great job!"
else:
    print"Unlucky pal! It was " +correct_answer+ "
question+1

3 个答案:

答案 0 :(得分:2)

我假设print (" ".join(strlist)) +是字符串。如果是这样,你需要他们周围的报价。将代码分开以使其更清晰也是一种很好的做法。

-

答案 1 :(得分:2)

答案:所需要的只是操作员周围的语音标记。

if operator == "+":
    correct_answer=random_number1+number2
elif operator == "-":
    correct_answer=random_number1-number2
else:
    correct_answer=random_number1*number2

答案 2 :(得分:0)

<块引用>

答案:


当你写 + 和 - 时,python 把它当作整数运算符的实数,并给它一个错误,因为没有数字。添加 " " 会将其定义为字符串,不应出现错误。


修正版:

if operator == "+":
    correct_answer=random_number1+number2
elif operator == "-":
    correct_answer=random_number1-number2
else:
    correct_answer=random_number1*number2