【发布时间】:2018-12-01 15:11:44
【问题描述】:
我正在尝试更改代码中的 3 件事。
使“答案”与用于“问题”的同一组 random.randomint 匹配。
让用户可以选择一个特定的运算符用于测验,而不是随机运算符。
对于减法运算符,确保第一个操作数大于第二个操作数,这样程序就不会给出否定答案。
感谢任何答案。 这是我的代码:
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 程序编写。 谢谢。
【问题讨论】:
-
欢迎来到 SO。请花时间阅读How to Ask 以及该页面上的其他链接。
-
为确保减法结果为正,您可以使用
absfunction。或者您可以先sort 值:small, big = sorted((4,3)); big - small。 -
您想将 questions 和 answers 代码保存在不同的文件中吗?
-
是的,问题和答案将在单独的文件中。第一个文件只是带有空格的随机问题,第二个文件是包含答案的相同随机问题。