Python随机数学的测验生成器程序,需要调整

时间:2018-12-01 15:11:45

标签: python windows file math

我正在尝试更改代码中的3件事。

  1. 使“答案”与用于“问题”的相同的random.randomint匹配。

  2. 为用户提供一个选项,以选择要用于测验的特定运算符,而不是随机运算符。

  3. 对于减法运算符,请确保第一个操作数大于第二个操作数,这样程序就不会给出否定答案。

任何答案都值得赞赏。 这是我的代码:

import random

print("Welcome to the maths quiz creator!")
CLASS = input("Please enter the class name: ")
NAME = input("Please enter your name: ")
NoofQ = int(input("How many questions for the quiz? "))

<-问题的第一文件->

output_file = open('{}_quiz.txt'.format(CLASS), 'w')
print("Class:", CLASS)
print("Teacher:", NAME)

output_file.write("Class: ")
output_file.write(CLASS)
output_file.write("\nTeacher: ")
output_file.write(NAME)

for question_num in range(1,NoofQ +1):
    ops = ['*','/','+','-']
    rand=random.randint(1,12)
    rand2=random.randint(1,12)
    operation = random.choice(ops)
    maths = eval(str(rand) + operation + str(rand2))
    Questions = '\n {}: {} {} {} {} {}'.format(question_num, rand, operation, rand2, "=", "________")

    print(Questions)
    output_file.write(Questions)
output_file.close()

<-答复的第二个文件->

output_file = open('{}_answers.txt'.format(CLASS), 'w')
print("Class:", CLASS)
print("Teacher:", NAME)

output_file.write("Class: ")
output_file.write(CLASS)
output_file.write("\nTeacher: ")
output_file.write(NAME)

for question_num in range(1, NoofQ +1):
    ops = ['*','/','+','-']
    rand=random.randint(1,12)
    rand2=random.randint(1,12)
    operation = random.choice(ops)
    maths = eval(str(rand) + operation + str(rand2))
    Answers = '\n {}: {} {} {} {} {}'. format(question_num, rand, operation, rand2, "=", int(maths))

    print(Answers)
    output_file.write(Answers)
output_file.close()

我对Python很陌生,使用程序Pycharm编写。 谢谢。

2 个答案:

答案 0 :(得分:0)

1使“答案”与用于“问题”的相同的random.randomint匹配。

您可以先构建一个列表,该列表将创建数字并将其用于问题和答案。

numbers = [(random.randint(1, 12), random.randint(1,12)) for _ in range(NoofQ)]

然后在问答中使用它:

for question_num in range(1,NoofQ +1): #i would prefer that question_num starts at 0
    ops = ['*','/','+','-']
    rand, rand2 = numbers[question_num-1] 

2为用户提供一个选择,以选择要用于测验的特定运算符,而不是随机运算符。

op = input("Please enter your operator (+, -, /, or *): ")

3对于减法运算符,请确保第一个操作数大于第二个操作数,这样程序就不会给出否定答案。

if operation == "-" and rand < rand2:
    rand, rand2 = rand2, rand

答案 1 :(得分:0)

要确保获得正的减法结果,可以使用abs function。或者,您可以先sort值:

answer = abs(4-3)
small, big = sorted((4,3))
answer = big - small. 

您制作一个xyz_quiz.txt文件,其中包含 answers 代码所需的所有信息。阅读测验文件,对于每个问题,使用str方法进行拆分和剥离,直到获得数学

>>> question = '1: 6 - 11 = ________'
>>> question, _ = question.split('=')
>>> question
'1: 6 - 11 '
>>> q_number, q = question.split(':')
>>> q_number
'1'
>>> q
' 6 - 11 '
>>> q = q.strip()
>>> q
'6 - 11'
>>>