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

我正在尝试更改代码中的 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 程序编写。谢谢你。


慕婉清6462132
浏览 159回答 2
2回答

www说

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&nbsp; &nbsp; ops = ['*','/','+','-']&nbsp; &nbsp; rand, rand2 = numbers[question_num-1]&nbsp;2 为用户提供一个选项来选择用于测验的特定运算符而不是随机运算符。op = input("Please enter your operator (+, -, /, or *): ")3 对于减法运算符,确保第一个操作数大于第二个操作数,以免程序给出否定答案。if operation == "-" and rand < rand2:&nbsp; &nbsp; rand, rand2 = rand2, rand

繁花不似锦

为了确保正减法结果,您可以使用abs 函数。或者您可以先对值进行排序:answer = abs(4-3)small, big = sorted((4,3))answer = big - small.&nbsp;您制作了一个xyz_quiz.txt包含答案代码所需的所有信息的文件。阅读测验文件,对于每个问题,使用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'>>>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python