Python - 使我的代码更经济

时间:2015-11-01 16:18:26

标签: python

我需要一些帮助才能让这段代码更经济 - 我相信,我可以减少很多行。

代码是一个测验,会提出10个问题,你的分数会在最后输出。

import random
studentname=input("what is your name?:")
score=0
trueanswer=0

def question():
    global operation
    global number1
    global number2
    global studentanswer
    global score
    number1=random.randrange(1,10)
    number2=random.randrange(1,10)
    operation=random.choice(["*","-","+"])
    print("what is", number1,operation,number2,"?:")
    studentanswer=int(input("insert answer:"))

def checking():
    global score
    if operation == "*":
        trueanswer = number1*number2
        if studentanswer == trueanswer:
            print("correct")
            score=score+1
        else:
            print("incorrect")
            score=score
    elif operation == "-":
        trueanswer = number1-number2
        if studentanswer == trueanswer:
            print("correct")
            score=score+1
        else:
            print("incorrect")
            score=score
    elif operation == "+":
        trueanswer = number1+number2
        if studentanswer == trueanswer:
            print("correct")
            score = score+1
        else:
           print("incorrect")
           score=score

def main():
    for i in range (10):
        question()
        checking()
    print("your score is", score)

main()

1 个答案:

答案 0 :(得分:-3)

您可以将整个检查功能减少到:

def checking():
    trueanswer = eval(str(number1)+operation+str(number2))
    if studentanswer == trueanswer:
        print("correct")
        score=score+1
    else:
        print("incorrect")
        score=score