jeudi 21 novembre 2019

if Loop Inside for Loop Not Working Correctly

I have a for loop first to go through the range of the length of a list of numbers.

After that I have an if loop checking that each number is less than or equal to the length of a variable.

When entering a single number (userLetterLocation) these loops work no problem. However when I enter multiple things like "2 and 6" or "3, 6", the if loop recognises a number is larger and displays "ERROR" but it then breaks out of the while loop and continues which obviously will break the program.

I believe the if loop is still updating keep_running with False which stops the while loop but I am unsure why?

def letterLocation(userWordHidden, compChoice):
    keep_running = True
    while(keep_running):
        userLetterLocation = input('Where does the letter(s) occur \
in the word?: ')
        letterPosition = re.findall("\d", userLetterLocation)
        letterPosition = [int(i) for i in letterPosition]
        print(len(letterPosition))

        for i in range(len(letterPosition)):
            if letterPosition[i] <= len(userWordHidden):
                keep_running = False
            else:
                print("ERROR")

    for i in letterPosition:
        userWordHidden[i-1] = compChoice

    print("Your Word:", end =" ")
    for i in range(len(userWordHidden)):
        print(userWordHidden[i], end =" ")

    print("\n")

    computerChoice(userWordHidden)

EDIT: Ok so I think I understand my issue. the if loop checks the first number and if it's ok, it will stop the while loop.

So off of that, does anyone know how I can check everything in the array before it marks keep_running as FALSE?

Aucun commentaire:

Enregistrer un commentaire