python - 奶牛和公牛游戏一直在说 0 头牛,0 头公牛?
问题描述
我正在做一个牛和牛游戏,你应该猜一个四位数。当我运行程序时,计算机一直说 0 头牛,0 头公牛,我不知道为什么或如何解决它
import random
print("Welcome to the cows and bulls game!")
number = [random.randint(0,9), random.randint(0,9), random.randint(0,9), random.randint(0,9)] counter = 0 teller1 = 0 teller2 = 0
while True :
guess = input("Enter a four digit number:")
bulls= 0
cows = 0
if cows == 4:
print("Congratulations, you have won the game. you only used:", counter, " attempts")
break
for i in range(4):
if guess[teller1] == number[teller2]:
cows = cows + 1
teller1 = teller1 + 1
teller2 = teller2 + 1
teller1 = 0
for i in range(4):
teller2 = teller1 - 1
for i in range(3):
if guess[teller1] == number[teller2]:
bulls = bulls + 1
teller1 = teller1 + 1
print(cows," cows, ", bulls," bulls")
counter = counter + 1
没有错误消息,但它一直说 0 头奶牛,0 头公牛。
解决方案
Your number
variable is a list of int
, but your guess
variable is a string. So when you do if guess[teller1] == number[teller2]
, you are comparing integers to strings, which is always false.
You can fix it by converting your string to a list of integers:
guess = [int(num) for num in input("Enter a four digit number:")]
Note that a proper solution would also validate the input given by the user (what happens if they type "12345"? "hello world"? nothing?).
推荐阅读
- javascript - 警告:无法执行 React 状态更新
- sql - 使用 Azure 数据流在同一个数据库表中加载两个文件
- android - 为什么我不能向这个 Observable 添加观察者?
- java - EclipseLink 的@OrderCorrection 对订单索引列没有影响
- ssl - 重新签发 SSL 证书但没有 .key 文件
- arrays - Clojure - 对 2D 向量进行垂直切片
- spinnaker - 大三角帆 REST API 补丁管道阶段
- javascript - 无法通过 jquery / javascript 设置图像 src
- wordpress - 如何修复我的 Wordpress 网站上的 CTA 按钮
- c++ - 用可变参数模板替换可变参数