Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

Python arithmetic quiz task 1

I have no idea why this code is not working, as you can see I'm trying to ask the user 10 questions display their score at the end. Everything works except that the score will always appear as a 0 or 1 at the end, even if more than 1 question was answered right. Here is my code:

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Each call to question() resets score to be 0. Remove the score=0 line from that function, and instead initialize it in main:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...