Python使我的代码更经济

2024-04-16 22:01:41 发布

您现在位置: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()

Tags: ifisdefrandomoperationglobalelsescore
1条回答
网友
1楼 · 发布于 2024-04-16 22:01:41

您可以将整个检查功能简化为:

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

相关问题 更多 >