Home > front end >  Rewriting loop without breaks
Rewriting loop without breaks

Time:11-26

Below is the code that I want to replicate without using break ///

while True:
    choice = input("Is it time to choose(Y/N)? ")
    if choice.upper() == "N": 
        break
    idx = random.randint(0, len(contents))
    fnd = False
    for i in range(3):
        for j in range(3):
            if table[i][j] == contents[idx]:
                table[i][j] = "SEEN"
                fnd = True
                break
        if fnd:
            break
    won = check_win(table)
    print_table(table)
    if won:
        print("The game has been won!!")
        break

Can't figure out, already tried using variables but can't make it work

CodePudding user response:

Let's handle this case by case. (I'm leaving initializing variables up to you, btw.)

while True:
    choice = input("Is it time to choose(Y/N)? ")
    if choice.upper() == "N": 
        break

The above break statement could be removed by having a playing variable. Change while True: to while playing, and then set playing to false if the player chooses; put the rest of the loop body in the else branch.

    idx = random.randint(0, len(contents))
    fnd = False
    for i in range(3):
        for j in range(3):
            if table[i][j] == contents[idx]:
                table[i][j] = "SEEN"
                fnd = True
                break
        if fnd:
            break

I'm taking the above two break statements to be independent of the top-level while loop, as that's the way it's currently coded. You could re-code these as two nested while loops that increment counters- while i < 3 && !fnd and while j < 3 && !fnd, though that's messy. The inner one could also be handled with index()

    won = check_win(table)
    print_table(table)
    if won:
        print("The game has been won!!")
        break

This last one is the easiest: Just change the loop condition to while playing && !won

That's messy, but it should be equivalent. I might be able to make it cleaner if I knew what you were trying to do with the code as a whole.

CodePudding user response:

You can use a flag instead:

w_flag = True
while w_flag:
    choice = input("Is it time to choose(Y/N)? ")
    if choice.upper() == "N": 
        w_flag = False
    
    if w_flag:
        idx = random.randint(0, len(contents))
        fnd = False
        i,j = 0,0
        i_flag = True
        while i < 3 and i_flag:
            j_flag = True
            while j < 3 and j_flag:
                if table[i][j] == contents[idx]:
                    table[i][j] = "SEEN"
                    fnd = True
                    j_flag = False
                j  = 1
            if fnd:
                i_flag = False
            i  = 1
        
        won = check_win(table)
        print_table(table)
        if won:
            print("The game has been won!!")
            w_flag = False
  • Related