Python-implemented simple arithmetic game instances and python arithmetic instances
This example describes a simple arithmetic game implemented by Python. Share it with you for your reference. The specific implementation method is as follows:
#! /Usr/bin/env pythonfrom operator import add, sub from random import randint, choiceops = {'+': add ,'-': sub} # define a dictionary MAXTRIES = 2 def doprob (): op = choice ('+ -') # Use choice to randomly select the operator nums = [randint () for I in range (2)] From '+-' # Use randint) generate a random number ranging from 1 to 10, and use range (2) nums twice. sort (reverse = True) # sort by ascending order ans = ops [op] (* nums) # Use the function pr = '% d % s % d =' % (nums [0], op, nums [1]) oops = 0 # oops for failure testing, when three times from While True: try: if int (raw_input (pr) = ans: print 'correct' break if oops = MAXTRIES: print 'answer \ n % s % d' % (pr, ans) break else: print 'encrect... try again 'oops + = 1 hour T (KeyboardInterrupt, EOFError, ValueError): print 'invalid ipnut... try again 'def main (): while True: doprob () try: opt = raw_input ('again? [Y] '). lower () if opt and opt [0] = 'N': break t (KeyboardInterrupt, EOFError): breakif _ name _ = '_ main __': main ()
The running result is as follows:
8 - 1 = 7correctAgain? [y]y7 - 1 = 6correctAgain? [y]y9 + 4 = 0incorrect... try again9 + 4 =
I hope this article will help you with Python programming.