python学习之——一个猜字游戏的小Demo

欢迎来到笨笨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
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值