Python算术测验任务1

时间:2015-10-31 18:23:17

标签: python

我不知道为什么这段代码不起作用,因为你可以看到我试图问用户10个问题在最后显示他们的分数。一切正常,除非得分始终显示为01,即使问题的回答超过1也是如此。 这是我的代码:

import random
studentname=input("what is your name?:")
def question():
    global operation
    global number1
    global number2
    global studentanswer
    global score
    operation=random.choice(["*","-","+"])
    score=0
    trueanswer=0
    number1=random.randrange(1,10)
    number2=random.randrange(1,10)
    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()

2 个答案:

答案 0 :(得分:2)

每次调用question()都会将score重置为0。从该函数中删除score=0行,然后在main中初始化它:

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

答案 1 :(得分:1)

您可以进行错误检查以查看您的计数变量是否已初始化。它不是最干净的解决方案,但可以胜任。

def checking():
try:
    global score
    score = score
except:
    global score
    score = 0

if operation == "*":
    trueanswer = number1*number2
    if studentanswer == trueanswer:
        print("correct")
        score=score+1