python 电脑猜数字
电脑猜数字是一个有趣的游戏。现在我们介绍怎样使用Python来实现这个游戏。
import random
print("欢迎来到电脑猜数字!")
print("请你在1到100之间随意选择一个数字")
low = 1
high = 100
count = 0
while True:
count += 1
guess = random.randint(low, high)
print("电脑猜的数字是:", guess)
ans = input("你的数字是大了(L),小了(S),正确(Y):")
if ans.strip().upper() == "L":
high = guess - 1
elif ans.strip().upper() == "S":
low = guess + 1
elif ans.strip().upper() == "Y":
print("电脑猜了", count, "次,就猜到了你心里的数字!")
break
else:
print("请输入 L、S 或 Y。")
在代码中,我们使用了random模块来生成1到100之间的随机数作为电脑猜想的数字。然后使用了while循环实现了屡次猜想,根据用户输入的提示对猜想的范围进行缩小,终究猜到正确数字。
如果你也喜欢这个游戏,可以试着自己运行一下它,看看能不能让电脑猜到你的心理数字!
文章来源:丸子建站
文章标题:python 电脑猜数字
https://www.wanzijz.com/view/57709.html