python实践项目四:猜数字游戏

题目要求:在1-20中随机生成一个数字,你来猜,只有6次机会。

举例一:

 #!/usr/bin/python
# -*- coding: UTF-8 -*- import random
secretNumber=random.randint(1,20)
print "I'm thinking of a number between 1 and 20."
times = 0
for i in range(1,7):
print "Take a guess:"
guess=int(input())
if guess<secretNumber:
print "Your guess is too low."
times+=1
elif guess>secretNumber:
print "Your guess is too high."
times += 1
else:
times += 1
break
if guess==secretNumber:
print "You are right! The number is:%d,you spend %d times" %(secretNumber,times)
else:
print "You are wrong,and the number is:%d" %secretNumber

运行结果:

python实践项目四:猜数字游戏

举例二:

 #!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
def guessNumber():
num=random.randint(1,20)
print "提前展示该随机数字:",num #方便测试可以先打印出该随机数字
guess=int(raw_input("我想了一个1-20的数字,给你6次机会你来猜。请猜一个数字:\n"))
times=0
while times<5:
if num==guess:
print "你猜对了!你花了%d次!" %(times+1)
break
if num > guess:
guess = int(raw_input("小了!请再猜:"))
times+=1
if num < guess:
guess = int(raw_input("大了!请再猜:"))
times+=1
if times==5:
print "6次机会用完了都没猜对!" guessNumber()

运行结果:

python实践项目四:猜数字游戏

上一篇:通过游戏学python 3.6 第一季 第九章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账号--锁定次数--菜单功能'menufile


下一篇:python 9*9乘法口诀 猜数字游戏