亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python隨機數學的測驗生成器程序,需要調整

Python隨機數學的測驗生成器程序,需要調整

慕婉清6462132 2021-09-02 20:10:28
我正在嘗試更改代碼中的 3 件事。使“答案”與用于“問題”的同一組 random.randomint 匹配。為用戶提供一個選項來選擇用于測驗的特定運算符而不是隨機運算符。對于減法運算符,確保第一個操作數大于第二個操作數,這樣程序就不會給出否定的答案。任何答案表示贊賞。這是我的代碼:import randomprint("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 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

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


查看完整回答
反對 回復 2021-09-02
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

為了確保正減法結果,您可以使用abs 函數?;蛘吣梢韵葘χ颠M行排序:


answer = abs(4-3)

small, big = sorted((4,3))

answer = big - small. 

您制作了一個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'

>>>


查看完整回答
反對 回復 2021-09-02
  • 2 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號