Goal:
1. Achieve two number of addition and subtraction
2. After 3 times, the respondents output the correct results, and ask the respondents whether to continue
1. Use regular functions to achieve two number of addition and subtraction games
The code is as follows:
#!/usr/bin/env python#-*-coding:utf-8-*-" "use regular functions to write quiz games" "ImportRandomdefAdd (x, y):returnX +ydefSub (x, y):returnX-ydefChuti (): Cmds= {'+': Add,'-': Sub} ops='+-'op=random.choice (OPS) Nums= [Random.randint (1,50) forIinchXrange (2)] Nums.sort (Reverse=True) Prompt='%s%s%s ='% (Nums[0], op, nums[1]) Anwser= Cmds[op] (*nums) Counter=0 whileCounter < 3: Try: Result=Int (raw_input (prompt))except: Continue ifAnwser = =Result:Print "Answer Right" Print "-"* 20 Break Else: Counter+ = 1Print "answer the wrong" Print "-"* 20Else: Print "the correct answer is:%s%s"%(prompt, anwser)if __name__=="__main__": whileTrue:chuti ()Try: yn= Raw_input ("Continue (y/n?)"). Strip () [0]exceptIndexerror:Continue except(keyboardinterrupt,eoferror): yn='N' ifYninch 'Nn': Print "End" Break
? Run code, test effect
[[email protected] python] # python new_mathgame.py= 5 Answer error --------------------+ = 2 answer error -------------------- + 3 answer error --------------------+ + = Continue (y/n?) Y15-1 = answer error --------------------15-1 = answer error --------------------15-1 = answer correct --------------------Continue (y/n?) N End
2. Using lambda anonymous function to implement two-digit addition and subtraction game
The code is as follows:
# !/usr/bin/env python # -*-coding:utf-8-*- " " use anonymous function lambda to write a quiz game " " Import Random
# def add (x, y): # return x + y# def sub (x, y): # return XY
defChuti (): cmds = {' + ': lambda x, y:x + y, '-': Lambda x, Y:x- y} Ops='+-'op=random.choice (OPS) Nums= [Random.randint (1,50) forIinchXrange (2)] Nums.sort (Reverse=True) Prompt='%s%s%s ='% (Nums[0], op, nums[1]) Anwser= Cmds[op] (*nums) Counter=0 whileCounter < 3: Try: Result=Int (raw_input (prompt))except: Continue ifAnwser = =Result:Print "Answer Right" Print "-"* 20 Break Else: Counter+ = 1Print "answer the wrong" Print "-"* 20Else: Print "the correct answer is:%s%s"%(prompt, anwser)if __name__=="__main__": whileTrue:chuti ()Try: yn= Raw_input ("Continue (y/n?)"). Strip () [0]exceptIndexerror:Continue except(keyboardinterrupt,eoferror): yn='N' ifYninch 'Nn': Print "End" Break
Python writes two numbers of addition and subtraction games