Python 猜100以内数字
引言
猜100以内数字游戏,程序内先设定被猜的数值。
用户给出的值偏小则给出提示“太小”;
用户给出的值偏大,给出提示“太大”,
最多只能猜5次。
猜中了给出提示“恭喜你!”;
如果5次都没猜正确,给出“结束,是否继续”。
如果继续,再给5次机会,如果不继续,则结束。
思路
完整代码
import random
# 按照要求随机一次数字
num = random.randint(0,100)
print("随机出来的数字为:", num)
count = 0
while count < 5:
try:
a = int(input("请输入一个整数:"))
iscorrect = False
if a == num:
iscorrect = True
print("恭喜你!")
break
elif a > num:
count += 1
print("太大")
else:
count += 1
print("太小")
# 五次回答完成之后,判断是否需要继续
if not iscorrect and count == 5:
str = input("结束,是否继续?继续请输入y:")
if str == "y":
count = 0
except ValueError:
print('请输入整数')