Advertisement
gruntfutuk

arithmetic challenge

Nov 15th, 2020
592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. from random import choice, randint
  2. import operator as op
  3.  
  4. target = 10
  5. success = 0
  6.  
  7. print('\n\nWelcome to a small arithmetic challenge')
  8. print(f'\n You will be asked for the answer to {target} questions')
  9. print('and after each answer you will be told if your are correct or')
  10. print('not. At the end, you will be told how many correct answers')
  11. print('you achieved.')
  12. print('\nNote: For /, division, the floor (integer) answer is required')
  13. print('(in face you should only provide whole number answers).\n')
  14.  
  15. # using a dictionary of operator symbols matched with their corresponding
  16. # python functions to call to get answer for expression
  17. ops = {'+': op.add, '-': op.sub, 'x': op.mul, '÷': op.floordiv}
  18. op_symbols = list(ops.keys())  # list of op symbols to choose from randomly
  19.  
  20. challenges = []  # generate 10 simple random arithmetic challenges
  21. for _ in range(target):  # need two random integers and random operator
  22.     challenges.append((randint(1, 10), randint(1, 10), choice(op_symbols)))
  23.    
  24. for q_num, (op1, op2, action) in enumerate(challenges, start=1):  # loop through challenges
  25.     try:  # in case user does not enter an integer, otherwise stops programme
  26.         answer = int(input(f'\nQ{q_num}: {op1} {action} {op2} = '))  # show plain english question
  27.     except ValueError:  # they didn't enter integer
  28.         print('Sorry, require whole number answers (rounded down for division)')
  29.     else:  # integer entered so can check answer
  30.         correct = ops[action](op1, op2)  # call the correct function and pass numbers
  31.         if answer == correct:
  32.             print('Correct. Well done.')
  33.             success += 1
  34.         else:
  35.             print('Sorry, that is wrong.')
  36.            
  37. print(f'\nYou achieved {success} correct answers for {target} questions\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement