题目要求:在1-20中随机生成一个数字,你来猜,只有6次机会。
举例一:
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 import random 5 secretNumber=random.randint(1,20) 6 print "I'm thinking of a number between 1 and 20." 7 times = 0 8 for i in range(1,7): 9 print "Take a guess:" 10 guess=int(input()) 11 if guess<secretNumber: 12 print "Your guess is too low." 13 times+=1 14 elif guess>secretNumber: 15 print "Your guess is too high." 16 times += 1 17 else: 18 times += 1 19 break 20 if guess==secretNumber: 21 print "You are right! The number is:%d,you spend %d times" %(secretNumber,times) 22 else: 23 print "You are wrong,and the number is:%d" %secretNumber
运行结果:
举例二:
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 import random 4 def guessNumber(): 5 num=random.randint(1,20) 6 print "提前展示该随机数字:",num #方便测试可以先打印出该随机数字 7 guess=int(raw_input("我想了一个1-20的数字,给你6次机会你来猜。请猜一个数字: ")) 8 times=0 9 while times<5: 10 if num==guess: 11 print "你猜对了!你花了%d次!" %(times+1) 12 break 13 if num > guess: 14 guess = int(raw_input("小了!请再猜:")) 15 times+=1 16 if num < guess: 17 guess = int(raw_input("大了!请再猜:")) 18 times+=1 19 if times==5: 20 print "6次机会用完了都没猜对!" 21 22 guessNumber()
运行结果: