繁体   English   中英

满足条件,但程序不会中断while循环

[英]conditions are met, but program not breaking out of while loop

即使输入“ 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)

它没有结束的原因是,除非它们都为假,否则满足while循环。 这行是您的麻烦所在:

while guess != num or guess != 'exit':

如果guess == 'exit' ,则会发生以下情况:

while False or True:

循环将继续运行,因为False or True返回True 为了解决这个问题,我将使用一个变量来保持游戏的运行,并在结束游戏时将其设置为false。

while running:

然后在循环中,如果guess =='exit'或num,则将运行设置为False ,程序将结束。

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

我在玩你的代码时发现错误,将and循环从a​​nd to更改为and

while guess != num or guess != 'exit':    

while guess != num and guess != 'exit':  

键入exit时,将使循环停止。

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM