Skip to content

Instantly share code, notes, and snippets.

@LieBtrau
Last active July 13, 2024 18:24
Show Gist options
  • Save LieBtrau/6c6cbb8b9637852688136797fb7dd26b to your computer and use it in GitHub Desktop.
Save LieBtrau/6c6cbb8b9637852688136797fb7dd26b to your computer and use it in GitHub Desktop.
Create math exercises for 1st to 3rd grade. Addition, subtraction, multiplication and division
#!/usr/bin/env python3
#
# This program prints out three colums of exercises, each time with the result next to it.
# Each column exists of 66 exercises.
#
# 1. Run the program
# 2. Print out the created text file to a DINA4-paper
# 3. Fold back the results of the first column
# 4. Fill in the results for the first column.
# 5. Unfold and check the results
# 6. Use the same method for the other two columns.
import os
import random
import sys
import datetime
import pytz
def addingSubtractingNatural(MAXINT):
'''
Generates a random addition or subtraction exercise with natural numbers (no negative numbers)
MAXINT: the maximum number to be used in the exercise
For first grade, MAXINT should be 20
For second grade, MAXINT should be 100
'''
answerfield = ' = ... \t|\t'
a = random.randint(0, MAXINT)
operations = ('+', '-')
operation = random.choice(operations)
if (operation == '+'):
b = random.randint(0, MAXINT-a)
c = a+b
return str(a) + ' + ' + str(b) + answerfield + str(c)
elif (operation == '-'):
b = random.randint(0, a)
c = a-b
return str(a) + ' - ' + str(b) + answerfield + str(c)
def multiplyDivideNatural(MAXINT):
'''
Generates a random multiplication or division exercise with natural numbers (no negative numbers)
MAXINT: the maximum multiplicand (or multiplier) to be used in the exercise
For second grade, MAXINT should be 10 (so the product is less than or equal to 100)
'''
answerfield = ' = ... \t|\t'
a = random.randint(0, MAXINT)
b = random.randint(0, MAXINT)
c = a*b
operations = ('x', ':')
operation = random.choice(operations)
if (operation == ':' and b == 0):
# avoiding division by zero
operation = 'x'
if (operation == 'x'):
# a*b = c
return str(a) + ' x ' + str(b) + answerfield + str(c)
elif (operation == ':'):
# c/b = a
return str(c) + ' : ' + str(b) + answerfield + str(a)
def main(argv):
# with open('./exercise_adding_subtracting.txt', 'w') as f1:
# for lines in range(66):
# f1.write(addingSubtractingNatural(20) + '\t\t' + addingSubtractingNatural(20) + '\t\t'+ addingSubtractingNatural(20) + os.linesep)
with open('./exercise_multiply_divide_'+ str(int(datetime.datetime.now(tz=pytz.utc).timestamp())) +'.txt', 'w') as f1:
for lines in range(66):
f1.write(multiplyDivideNatural(10) + '\t\t' + multiplyDivideNatural(10) +
'\t\t' + multiplyDivideNatural(10) + os.linesep)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment