【发布时间】:2019-08-26 13:24:49
【问题描述】:
这里根据条件设置牛的值。如果 cows 等于 4 那么 while 循环应该中断。 但这里 break 被视为不存在。
import random
r = random.randint
def get_num():
return "{0}{1}{2}{3}".format(r(1, 9), r(1, 9), r(1, 9), r(1, 9))
n = get_num()
print(n)
n = [z for z in str(n)]
def game():
cows = 0
bulls = 0
print()
usr_num = [i for i in input("enter:\n")]
usr_set = set(usr_num)
while True:
for x in usr_set:
if usr_num.count(x) >= n.count(x):
cows += n.count(x)
bulls += usr_num.count(x) - n.count(x)
elif usr_num.count(x) < n.count(x):
cows += usr_num.count(x)
bulls += n.count(x) - usr_num.count(x)
print("cows: ", cows, " bulls: ", bulls)
if cows == 4:
print("correct!")
break
else:
game()
game()
当 cows = 4 时,correct 被打印,但 break 没有显示效果
如果我们稍微改变一下代码。 如果我们把 4(If 语句)
代替 cowsdef game():
cows = 0
bulls = 0
print()
usr_num = [i for i in input("enter:\n")]
usr_set = set(usr_num)
while True:
for x in usr_set:
if usr_num.count(x) >= n.count(x):
cows += n.count(x)
bulls += usr_num.count(x) - n.count(x)
elif usr_num.count(x) < n.count(x):
cows += usr_num.count(x)
bulls += n.count(x) - usr_num.count(x)
print("cows: ", cows, " bulls: ", bulls)
if 4 == 4:
print("correct!")
break
else:
game()
game()
那么 break 就起作用了。
【问题讨论】:
-
欢迎来到Stack Overflow!
NameError: name 'n' is not defined请edit 您的问题包含足够的代码,以便我们可以复制问题。请同时包含一些示例输入。 -
由于递归,你同时处于多个循环中。
-
game()设置一对 local 变量,而不是循环中使用的变量。 (或者你的代码中的缩进有问题吗?) -
我们无法复制您的问题,因为您没有提供minimal reproducible example:如果您需要帮助,您必须提供丢失的代码以及产生问题的有效输入。还请非常仔细检查以确保缩进正确。
标签: python while-loop break