# # Test the user's addition and multiplication abilities using 10 random # questions involving small integers. # import random # # Generate a random question involving small integers and either addition # or multiplication. # # Parameters: (None) # # Returns: # operand 1: The operand to the left of the operator # operator: Either + or * # operand 2: The operand to the right of the operator # ans: The correct answer to the question # def randomQuestion(): # Pick two random integers op1 = random.randrange(1, 11) op2 = random.randrange(1, 11) # Pick a random operator operator = randomOperator() # Compute the correct answer for the problem if operator == "+": ans = op1 + op2 else: ans = op1 * op2 # Return all 4 parts of the question return op1, operator, op2, ans # # Randomly select an operator, either + or * # # Parameters: (None) # # Returns: An operator, either + or * # def randomOperator(): # Pick a random integer i = random.randrange(2) # If the integer is 0 that represents +, otherwise * if i == 0: return "+" else: return "*" # # Quiz the user on basic arithmetic. # # Parameters: (None) # # Returns: (None) # def main(): numCorrect = 0 # Do 10 times for qnum in range(1, 11): # Create a random question o1, op, o2, correct = randomQuestion() # Display the question & read the answer from the user print("Question %d: What is %d %s %d?" % (qnum, o1, op, o2)) answer = int(input()) # Report whether the user's answer was right or wrong if answer == correct: print("That's correct!") numCorrect = numCorrect + 1 else: print("Nope... the correct answer was", correct) print("Your score was", numCorrect, "out of 10") # Prevent the main program from executing if this file is imported into # another program. if __name__ == "__main__": main()