This article is an example of a simple arithmetic game implemented by Python. Share to everyone for your reference. The implementation method is as follows:
#!/usr/bin/env pythonfrom operator import Add, sub from random import randint, Choiceops = {' + ': ad D, '-': Sub} #定义一个字典MAXTRIES = 2 def doprob (): op = Choice (' +-') #用choice从 ' + + ' Random selection operator nums = [Randint (1,10) for I in RA Nge (2)] #用randint (1,10) randomly generates a number from 1 to 10, randomly two times using range (2) nums.sort (reverse=true) #按升序排序 ans = ops[op] (*nums) #利用函数 PR = ' %d%s%d = '% (Nums[0], op, nums[1]) oops = 0 #oops用来计算failure测试, when three times automatically gives the answer while True:try:if Int (raw_input (PR)) = = Ans:print ' correct ' break if oops = = Maxtries:print ' answer\n%s%d '% (pr, ans) Brea K else:print ' Incorrect ... try again ' oops + 1 except (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 except (Keyboardinterrupt, Eoferror): breakif __name__ = = ' __main__ ': Main ()
The results of the operation are as follows:
Hopefully this article will help you with Python programming.