您的位置:首页 > 编程语言 > Python开发

python核心编程-函数参数传递

2015-12-01 00:07 411 查看
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from operator import add,sub
from random import randint,choice

ops = {'+':add,'-':sub}
MAXTRIES = 2

def doprob():
op = choice('+-')
nums = [randint(1,10) for i in range(2)]  #在1-10中选择2个数
print 'nums[0]:%d,nums[1]:%d'% (nums[0],nums[1])
nums.sort(reverse=True)  #连个数大小排序
ans=ops[op](*nums)   #两个数的算术结果
print 'ans:%d'% ans
pr='%d %s %d='%(nums[0],op,nums[1])  #输出类似:8+3=
oops=0
while True:
try:
if int(raw_input(pr)) == ans:  #如果输入正确
print 'correct'
break
if oops == MAXTRIES:  #输入错误次数达到最大,给出正确答案
print 'answer\n%s%d'%(pr,ans)
else:
print 'incorrect ... try agin'
oops += 1
except (KeyboardInterrupt,EOFError,ValueError):
print 'invalid input ... try again'

def main():
while True:
doprob()
try:
opt = raw_input('Again? [y]').lower()
if opt and opt[0] == 'n':
break
except (KeyboardInterrupt,EOFError):
break
if __name__ == '__main__':
main()


D:\Python27\test>func3.py
nums[0]:6,nums[1]:7
ans:1
7 - 6=2
incorrect ... try agin
7 - 6=1
correct
Again? [y]y
nums[0]:6,nums[1]:7
ans:13
7 + 6=13
correct
Again? [y]n

D:\Python27\test>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: