├── README.md └── math_Quiz_game.py /README.md: -------------------------------------------------------------------------------- 1 | # python-Math-Quiz 2 | -------------------------------------------------------------------------------- /math_Quiz_game.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | # consumer 4 | 5 | 6 | def calculateAnswer(lhs, rhs, oparator): 7 | if oparator == '+': 8 | return lhs + rhs 9 | elif oparator == '-': 10 | return lhs - rhs 11 | elif oparator == '*': 12 | return lhs * rhs 13 | elif oparator == '/': 14 | return lhs / rhs 15 | elif oparator == '**': 16 | return lhs ** rhs 17 | raise Exception('Unkown Operator') 18 | 19 | 20 | def generatorQuestion(): 21 | ops = "/*-+" 22 | opIndex = randint(0, len(ops) - 1) 23 | operator = ops[opIndex] 24 | lhs = randint(0, 10) 25 | rhs = randint(0, 10) 26 | while(rhs == 0 and operator == "/"): 27 | rhs = randint(0, 10) 28 | 29 | return lhs, rhs, operator 30 | 31 | 32 | def isAccurateEnoughAnswer(giveAnswer, correctAnswer, tolerance=0.01): 33 | difference = abs(float(giveAnswer) - float(correctAnswer)) 34 | return difference <= tolerance 35 | 36 | 37 | totalQuestion = 10 38 | correct = 0 39 | 40 | for i in range(totalQuestion): 41 | question = generatorQuestion() 42 | correctAnswer = calculateAnswer(question[0], question[1], question[2]) 43 | playerAnswer = input('{0} {2} {1} = '.format( 44 | question[0], question[1], question[2])) 45 | if(isAccurateEnoughAnswer(correctAnswer, playerAnswer)): 46 | print('Correct') 47 | correct += 1 48 | else: 49 | print('wrong. Correct answer = ' + str(correctAnswer)) 50 | 51 | print("You got {0} correct answer out of {1}. or {2}% correct".format( 52 | correct, totalQuestion, correct/totalQuestion*100)) 53 | --------------------------------------------------------------------------------