Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import choice, randint
- import operator as op
- target = 10
- success = 0
- print('\n\nWelcome to a small arithmetic challenge')
- print(f'\n You will be asked for the answer to {target} questions')
- print('and after each answer you will be told if your are correct or')
- print('not. At the end, you will be told how many correct answers')
- print('you achieved.')
- print('\nNote: For /, division, the floor (integer) answer is required')
- print('(in face you should only provide whole number answers).\n')
- # using a dictionary of operator symbols matched with their corresponding
- # python functions to call to get answer for expression
- ops = {'+': op.add, '-': op.sub, 'x': op.mul, '÷': op.floordiv}
- op_symbols = list(ops.keys()) # list of op symbols to choose from randomly
- challenges = [] # generate 10 simple random arithmetic challenges
- for _ in range(target): # need two random integers and random operator
- challenges.append((randint(1, 10), randint(1, 10), choice(op_symbols)))
- for q_num, (op1, op2, action) in enumerate(challenges, start=1): # loop through challenges
- try: # in case user does not enter an integer, otherwise stops programme
- answer = int(input(f'\nQ{q_num}: {op1} {action} {op2} = ')) # show plain english question
- except ValueError: # they didn't enter integer
- print('Sorry, require whole number answers (rounded down for division)')
- else: # integer entered so can check answer
- correct = ops[action](op1, op2) # call the correct function and pass numbers
- if answer == correct:
- print('Correct. Well done.')
- success += 1
- else:
- print('Sorry, that is wrong.')
- print(f'\nYou achieved {success} correct answers for {target} questions\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement