Computation drill python

This time, we will use a text file to create a binary operation drill for single-digit natural numbers. The environment is anaconda. The code I wrote is as follows.

Code and output result

Calculation drill


import random

with open("keisan.txt","w") as f:
    answer = []
    for cnt in range(10):
        num1 = random.randint(1,9)
        num2 = random.randint(1,9)
        question = str(num1) + " + " + str(num2) + " = "
        answer.append(num1+num2)
        f.write(question+"\n")
    f.write("\nA. ")
    for ans in answer:
        f.write(str(ans) + " ")

Output result


5 + 1 = 
5 + 2 = 
3 + 3 = 
2 + 6 = 
1 + 5 = 
4 + 8 = 
6 + 1 = 
8 + 4 = 
6 + 7 = 
6 + 4 = 

A. 6 7 6 8 6 12 7 12 13 10 

flow

I will explain the flow of the program.

Open text file


with open("keisan.txt","w") as f:

First, import the random module </ b> to get a single digit natural number. Then use the with statement </ b> to output to a text file, name the file "keisan.txt" and open it in write mode.

Writing an expression


answer = []
for cnt in range(10):
        num1 = random.randint(1,9)
        num2 = random.randint(1,9)
        question = str(num1) + " + " + str(num2) + " = "
        answer.append(num1+num2)
        f.write(question+"\n")
    f.write("\nA. ")

Here, the actual addition is written. We will also output the answer, so prepare a list. The randint function </ b> that generates the integers of the random module is used to generate natural numbers from 1 to 9. The question sentence is stored in the question, but if you use the operator, it will be calculated arbitrarily </ b>, so it is converted to a character string and stored. The answer is to use the append </ b> method and add it to the list. Then, the calculation formula stored in question is written by the write </ b> method. Output with line breaks for easy viewing.

Writing the answer


 for ans in answer:
        f.write(str(ans) + " ")

Finally, the list of answers stored in answer is output in order by the for statement.

Looking back

I've written and read text files using C language in the past, but with python it's very easy because using the with statement makes you unaware of closing the file. Since this code is only a binary operation of addition, I would like to expand the function of this calculation drill by freely selecting the operation and specifying the number of digits in the future. If you have any comments or questions, please feel free to comment.

Recommended Posts