欢迎来到笨笨1号的python小程序
一边学习python的过程中,一边练习写了几个小程序,以下是一个猜数字的小游戏。
实现的功能:程序随机一个0~20的整数,玩家来猜。玩家一共有6次机会,每猜一个数字,程序会提示该数字比正确的数字大还是小?
以下是完整的代码:
#!/usr/bin/env python3
#python中'''表示多行注释
'''
function: this is a game: guess the number that I am thinking now
author : Kate BEN
date : 2016-6-9
'''
#导入random模块
import random
#通过random.randin随机一个0~20整数,并赋值给变量secretNumber
secretNumber = random.randint(0,20)
print("I am thinking a number from 0~20,please guess it! you have six chances.")
#the player guess the number with six chances
#for循环遍历1~6
for guessTimes in range(1,7):
print("Now,take the guess please:")
#通过键盘输入字符串,并转换成int类型赋值给gussNumber变量
guessNumber = int(input())
#判断玩家所猜的数字和正确的数字是否相等
if guessNumber < secretNumber:
print("the number you guess is too low ~")
elif guessNumber > secretNumber:
print("the number you guess is too large ~")
else:
print("Greate! you guess the rignt number with " + str(guessTimes)+ " tries!")
break
#猜数字结束(玩家猜中或者6次机会用完),通知玩家最终结果
if guessNumber == secretNumber:
print("You have win the game!")
else:
print("Sorry, you didn't guess the right number within six chances~~")
print("the number I was thinking of was: " + str(secretNumber))
运行结果如下:
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/benzhonghai/PycharmProjects/WebCrawler/GuessNumber.py
I am thinking a number from 0~20,please guess it! you have six chances.
Now,take the guess please:
15
the number you guess is too large ~
Now,take the guess please:
10
the number you guess is too large ~
Now,take the guess please:
5
the number you guess is too large ~
Now,take the guess please:
3
the number you guess is too large ~
Now,take the guess please:
2
the number you guess is too large ~
Now,take the guess please:
1
Greate! you guess the rignt number with 6 tries!
You have win the game!
Process finished with exit code 0