python實踐項目四:猜數字游戲


題目要求:在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次機會你來猜。請猜一個數字:\n"))
 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()

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM