做出一个对弈猜数字游戏
import random #导入随机数方法
import time
bomb = random.randint(1, 1000) #范围
start = 0
end = 1000
while 1 == 1:
people = int(input('请输入{}到{}之间的数:'.format(start, end)))
if people > bomb:
print('大了')
end = people
elif people < bomb:
print('小了')
start = people
else:
print('BOOM!!!')
break
print('等待电脑了输入{}到{}之间的数:'.format(start, end))
time.sleep(1)
com = random.randint(start + 1, end - 1)
print('电脑输入:{}'.format(com))
if com > bomb:
print('大了')
end = com
elif com < bomb:
print('小了')
start = com
else:
print('BOOM!!!')
break
运行结果如下:
如果猜一百以内的数,且有次数限制,那么又该怎样做?
有次数限制的猜数游戏
import random
realnum = random.randint(1, 100)
i = 0
while i <10:
guessnum = int(input("请输入一个1-100之间的数"))
i=i+1
if guessnum == realnum:
print("恭喜你,猜对了!你总共用了",i,"次")
break
elif guessnum<realnum:
print("你猜小了!")
elif guessnum>realnum:
print("你猜大了!")
else:
print("你已经猜错10次,没有机会了!")
运行结果如下:
简单的while循环出1+2+…+100
i = 1
r =0
while i<=100:
r += i
i +=1
print(r)
输出结果为: