即使输入“ exit”或num
,程序也不会中断while循环。在函数的底部,我尝试使用guess == num
进行检查,然后返回true。函数最底层的代码是此函数的基本结构,并且该代码可以正常工作。不打破while循环的问题是否与函数中的两个for循环有关?谢谢。
def cowsAndBulls():
guess = ''
num = str(random.randint(1000, 9999))
while guess != num or guess != 'exit':
guess = input('Please enter a guess for a 4-digit number (\'exit\' to leave): ')
numL = [digit for digit in num]
guessL = [digit for digit in guess]
cow = 0
bull = 0
for digit in guessL:
if digit in numL and guessL.index(digit) == numL.index(digit):
cow = cow + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
for digit in guessL:
if digit in numL and guessL.index(digit) != numL.index(digit):
bull = bull + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
print(num)
print('Number of cows: ' + str(cow))
print('Number of bulls: ' + str(bull))
print(guess == num)
cowsAndBulls()
guess = ''
num = str(random.randint(0,5))
while guess != num:
guess = input()
print(num)
答案 0 :(得分:5)
之所以没有结束,是因为除非两个都为假,否则while循环就可以满足了。这行是您麻烦的出处:
while guess != num or guess != 'exit':
如果guess == 'exit'
,将发生以下情况:
while False or True:
因为False or True
返回True
,所以循环将继续运行。
为了解决这个问题,我将使用一个变量来保持游戏的运行,并在您想结束游戏时将其设置为false。
while running:
然后在循环内,如果guess =='exit'或num,则将运行设置为False
,程序将结束。
答案 1 :(得分:2)
import random
def cowsAndBulls():
guess = ''
num = str(random.randint(1000, 9999))
while guess != num and guess != 'exit':
guess = input('Please enter a guess for a 4-digit number (\'exit\' to leave): ')
numL = [digit for digit in num]
guessL = [digit for digit in guess]
cow = 0
bull = 0
for digit in guessL:
if digit in numL and guessL.index(digit) == numL.index(digit):
cow = cow + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
for digit in guessL:
if digit in numL and guessL.index(digit) != numL.index(digit):
bull = bull + 1
guessL[guessL.index(digit)] = 'G'
numL[numL.index(digit)] = 'N'
print(num)
print('Number of cows: ' + str(cow))
print('Number of bulls: ' + str(bull))
print(guess == num)
cowsAndBulls()
将您的or
更改为and
。
答案 2 :(得分:-1)
我正在处理您的代码,发现错误,将您的while循环从和或更改为和
while guess != num or guess != 'exit':
到
while guess != num and guess != 'exit':
一旦键入exit,将使循环停止。
祝你好运!