Python数学测验

时间:2015-05-05 14:11:41

标签: python

我正在用python创建一个数学测验但是我遇到了一些麻烦,如果有人可以帮助我,我会很感激。 我需要程序向用户询问10个问题,然后计算10个用户的分数。但是我的程序没有这样做,而是提出了12个问题并且没有计算用户分数。

到目前为止,这是我的代码的复制和粘贴:

import random
import operator

def quiz():

    print('Welcome. This is a 10 question math quiz\n')
    name = input("Please enter your name")
    print("Hello", name," Let's begin the quiz!")
    score = 0
    for i in range(10):
        correct = askQuestion()
        if correct:
            score += 1
            print('Correct!\n')
            print(score)
            break
        else:
            print('Incorrect!\n')

    return 'Your score was {}/10'.format(score)


def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def randomCalc():
    ops = {'+':operator.add,
    '-':operator.sub,
    '*':operator.mul,
    '/':operator.truediv}
    num1 = random.randint(0,11)
    num2 = random.randint(1,11)   
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?\n'.format(num1, op, num2))
    return answer
    print(score)

quiz()
askQuestion()
randomCalc()

5 个答案:

答案 0 :(得分:1)

您的代码段中存在一些逻辑和表示错误,您遇到的主要问题是获得12个问题而非10个问题,这是因为您最后调用了askQuestion()randomCalc()quiz()函数本身调用它们时的代码。另一个问题是在break循环中使用了for语句,我想你混淆了continuebreak语句,break用于退出循环,但是在Python for循环的情况下,您不需要任何break/continue构造。带家具的代码可能看起来像

import random
import operator

def quiz():

    print('Welcome. This is a 10 question math quiz\n')
    name = input("Please enter your name")
    print("Hello", name," Let's begin the quiz!")
    score = 0
    for i in range(10):
        correct = askQuestion()
        if correct:
            score += 1
            print('Correct!')
            print "Score",(score),"\n"
        else:
            print('Incorrect!')
            print "Score",(score), "\n"

    print 'Your score was {}/10'.format(score)


def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def randomCalc():
    ops = {'+':operator.add,
    '-':operator.sub,
    '*':operator.mul,
    '/':operator.truediv}
    num1 = random.randint(0,11)
    num2 = random.randint(1,11)   
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?'.format(num1, op, num2))
    return answer

quiz()
#askQuestion()
#randomCalc()

答案 1 :(得分:0)

这可能是不合时宜的(因为在撰写本文时)您的缩进没有正确完成,但我相信您需要更改此内容:

quiz()
askQuestion()
randomCalc()

对此:

print(quiz())

正如你现在所拥有的,"你的分数是......"永远不会打印,因为return结尾处有quiz个字符串,但您从不对结果做任何事情。并且您提出了12个问题而不是10个问题,因为您在致电askQuestion后不必要地拨打randomCalcquiz

答案 2 :(得分:0)

我在输出中进行了一些更改,您应该将.format用作变量,而不是其他任何内容。

现在应该可以工作了...

import random
import operator

    def quiz():

    print('Welcome. This is a 10 question math quiz\n')
    name = input("Please enter your name\n")
    print("Hello", name,"\n Let's begin the quiz!")
    score = 0
    for i in range(10):
        correct = askQuestion()
        if correct:
            score = score + 1
            print('Correct!')
            print ("Score is {}".format(score))
        else:
            print('Incorrect!')
            print ("Score is {}".format(score))

     print("{}, your score was {}/10".format(name, score))


def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def randomCalc():
    ops = {'+':operator.add,
    '-':operator.sub,
    '*':operator.mul,
    '/':operator.truediv}
    num1 = random.randint(0,11)
    num2 = random.randint(1,11)   
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?'.format(num1, op, num2))
    return answer

quiz()
#askQuestion()
#randomCalc()

答案 3 :(得分:0)

这是一个易于理解的数学测验。尽管我是初学者(也是14岁),但我还是创建了此测验,这意味着您应该能够理解它。 此测验还具有一个倒计时(可选),我添加了该倒计时以使测验更有趣,并且它拒绝任何非整数值:)

from random import randint 
import time
name = input("Please enter your name: ")
print("Hello %s, Let's begin the quiz!" % name)

time.sleep(3)
for x in range(0,3):
    print(3 - x)
    time.sleep(1)
print("GO!\n")

start_time = time.time()
score = 0

#0,10 is the number of questions you want.
for x in range(0, 10):
    #30,50 are values which decides the range of the two numbers. eg. 39,44
    y = randint(30,50)
    z = randint(30,50)

    while True:
        try:
            ans = int(input("Question %s: What is %s + %s = " % (x + 1, y, z)))
        except ValueError:
            print("Sorry, I didn't get that.")
            continue
        else:
            break

    if y + z == ans:
        score = score + 1
        print("Correct\n")
    else:
        print("Wrong\n")

elapsed_time = time.time() - start_time

print("\n\n%s, you scored %s/10!\nYou took %ss to complete the quiz! " % (name,score,round(elapsed_time)))

答案 4 :(得分:0)

我也有一个测验:

from random import randint
    def main():
        # -----------------------------------------------------
        #  creates variables
        correct = 0
        tries = 0
        problemsd = 0
        num1 = randint(1,5)
        num2 = randint(1,5)
        # -----------------------------------------------------
        # main loop
        print('line twelve')
        while tries < 3:
            try:
                answer = input(str(num1) + ' + ' + str(num2) + ' = ')
                answer = int(answer)
                print('line seventeen')
                if answer == num1 + num2:
                    print('Correct!')
                    print('line nineteen')
                    problemsd += 1
                elif answer != num1 + num2:
                    print('Try again!')
                    print()
                    tries += 1
                print('The answer is ' + str(num1 + num2))
                num1 = randint(1,5)
                num2 = randint(1,5)
            except KeyboardInterrupt:
                break
        print('\n' + str(problemsd) + '/' +str(correct))
    main()