zoukankan      html  css  js  c++  java
• # 71-使用函数编写数字游戏

随机从1到100随机取2个数值进行随机的相加减，输错3次给答案。

```from random import randint,choice

return x + y

def sub(x,y):  # 定义减函数
return x - y

def exam():
nums = [randint(1,100) for i in range(2)]  # 随机取2个数值放在列表里
nums.sort(reverse=True)  # 列表降序排列
op = choice('+-')  # 随机选择加或者减
result = cmds[op](*nums)  # 随机值相加减的结果
prompt = "%s %s %s = " %(nums[0],op,nums[1])
tries = 0

while tries < 3:
try:
except:
continue

print("You are right!")
break

else:
print("You are wrong!")
tries += 1
else:  # 猜对了直接跳出循环，3次全猜错了才执行，给出答案。
print("%s %s" %((prompt,result)))

if __name__ == '__main__':
while True:
exam()
try:
yn = input("Continue(y/n)? ").strip()[0]
print(yn)
except IndexError:
continue
except (KeyboardInterrupt,EOFError):
print()
yn = 'n'
if yn in 'nN':
break```

结果输出：

```62 - 29 = 20
You are wrong!
62 - 29 = 30
You are wrong!
62 - 29 = 50
You are wrong!
62 - 29 =  33
Continue(y/n)? y
y
25 + 16 = 41
You are right!
Continue(y/n)? n
n```
• 相关阅读:
Spring Boot第四弹，一文教你如何无感知切换日志框架？
Spring Boot 第三弹，一文带你了解日志如何配置？
UVa 1625
UVa 11584
UVa 11400
UVa 12563
UVa 116
UVa 1347
UVa 437
UVa 1025
• 原文地址：https://www.cnblogs.com/hejianping/p/10969204.html