Python实现猜数字游戏

Python实现猜数字游戏

zhangfan080816


1.总体概览


import random
G = 0  #you input number
t = 0  #times
a = 0
b = 0

print("Guess a number")
print("Input the range of number")
a = input("From: ")
b = input("To: ")
a = int(a)
b = int(b)
print("There are only 5 times")

N = random.randint(a,b)  #Guess number

while G != N and t < 6:  #t<6 limit the time
    G = int(input("Input your number:"))  #input the number
    
    if G > N:
        print("Too high")
    elif G < N:
        print("Too low")
    elif G == N:
        break
    #check the number

    t = t + 1

if G == N:
    print("You got it. It's ", N)
else:
    print('No more guesses. The number is ', N)

这段代码实现了猜数字游戏,并且只有五次机会和自选限定猜数字的范围。


2.输入

首先我们要创建一个随机数:

import random
a = 0
b = 0

a,b是限定随机数生成的范围。

接下来我们先让用户输入随机数生成的范围,并将其改为整数的形式:

a = input("From:")
b = input("To:")
a = int(a)
b = int(b)

生成随机数:

N = random.randint(a,b)

N就是程序生成的随机数。


3.处理

接下来判断用户输入的正确与否:

while G != N and t < 6:  #t<6 limit the time
    G = int(input("Input your number:"))  #input the number
    
    if G > N:
        print("Too high")
    elif G < N:
        print("Too low")
    elif G == N:
        break
    #check the number

    t = t + 1

这里我们用while来进行一个循环,t 是用户输入的次数(5次)

G 是用户猜的数,在while循环中重复输入。

G 和 t需要先在程序开头初始化:

G = 0
t = 0

用 if 来判断用户猜对没有,若过大或者过小则提醒用户,若猜对就退出循环(break)。

循环末尾每猜错一次就记一次,到达五次(while循环条件)退出:

t = t + 1

4.输出

程序末尾若用户猜对则告诉用户猜对了,若没有则告诉用户失败和随机数是多少。

if G == N:
    print("You got it. It's ", N)
else:
    print('No more guesses. The number is ', N)

到此程序就结束了,希望能帮到初学python的同学。

END~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值