利用random实现猜数字游戏
随机生成0到8的整数,人机交互进行猜数字游戏。记录直到猜中次数
from random import randint
preinstall = randint(0,9)
order=1
while True :
guess = input("请输入所猜数:\n")
try :
guess=int(guess)
except Exception as e :
guess=input("请重新输入一个整数:\n")
finally :
guess=int(guess)
if guess < preinstall :
print("遗憾,太小了")
order+=1
elif guess > preinstall :
print("遗憾,太大了")
order+=1
else :
print("经过{}次,你猜中了!确实是{}".format(order,preinstall))
break
运行效果展示: