Home > database >  How do i get out of this nested loop
How do i get out of this nested loop

Time:04-08

I have been trying to get out of this nested loop I coded....please forgive me if the code is a bit too long but the actual important part has been commented at the last but one area of the code please help. import random import time import math

# main

while True:
    print('Only a maximum of three players are allowed in this game. A single player plays 
with cpu')
    print('1. Single Player\n2. Double Players\n3. Triple players')
    print("Let's Start")
    player_select = input('How many players will be playing ths game?: ')
    single_score = []  # keep scores of player
    cpu_score = []  # keep scores of CPU

    while True:
        lst = ['Rock', 'Paper', 'Scissors']  # holding the random three words
        if player_select == '1' or player_select.lower() == 'single player':
            randomize = random.choice(lst)  # create a random choice out of the list
            for i in last:
                print(i)  # display rock paper scissors
                time.sleep(1)
            print(randomize)
            guess = input('guess rock, paper or scissors: ')  # demanding for a guess

            if guess.lower() == randomize.lower():  # what should happen if guess is right
                single_score.append(1)  # add 1 to the single_score list

                print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")

            elif guess.lower() != randomize.lower():
                cpu_score.append(1)

                print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
            print("Press 'Enter to continue'\n1. Change number of players(p)\n2. Exit(e) ")
            question = input('Enter your choice: ')
            if question == '':
                continue
            elif question.lower() in ['change number of players', 'p'] or question == '2':
                print('Lets start all over')
            #how do i get out of this to the intitial while loop?
            elif question.lower() in ['exit', 'e'] or question == '3':
                print('Total score of Player1', sum(single_score), '\n Total score of Player CPU', 
sum(cpu_score))

CodePudding user response:

The best way to do this is to use boolean check in your while loop :

check1 = True
check2 = True
while check1:
   ...
   while check2:
       if some_stop_condition_for_the_iner_loop:
           check2 = False
       if some_stop_condition_for_the_outer_loop:
           check1 = False
           check2 = False

In this way you can easily control your execution flow. You can also use the keyword break that will allow you to stop the current loop you're in, but if there is neested loop, it will only break the deeper one, so boolean check are often the best solution.

  • Related