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~