Python 猜数字 小游戏

以后每天开始学一点PYTHON 语言


就是输入一个数字,然后跟电脑选定的数字进行比较。

刚开始我是这样写的

computer = 25
you = int(raw_input('please input a number:'))
if you > computer:
      print 'too big'
elif you < computer:
      print 'too small'
else:
      print' yes,you are right answer!'



是这样我们只能猜一次游戏就结束了,现在改进下只有你猜中数字了猜数字游戏才结束

computer = 25
while True:
     you = int(raw_input('please input a number:'))
      if you > computer:
            print '%d is too big' %you
      elif you < computer:
            print '%d is too small'%you
      else:
            print' yes,you are right ,the answer is %d!' %you
            break
用python写一个猜数字的小游戏

前面两个都是我们事先给定了一个数字,这还不是真正的猜数字,那么我们事先不知道电脑选了是什么数字改怎么猜呢?其实也很简单就是加一个随机选择模块,让电脑自己随机选择一个数字。
from random import randint
computer = randint(1,100)
while True:
you = int(raw_input('please input a number in 1-100:'))
if you > computer:
      print '%d is too big' %you
elif you < computer:
      print '%d is too small'%you
else:
      print' yes,you are right ,the answer is %d!' %you
      break
用python写一个猜数字的小游戏

OK,整个程序结束。
random随机选择模块
random.randint(a,b)随机选择整数,a是下限,b是上限。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值