Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make the loop continue even after a part of it breaks in python

The code below ends after a player has reached a value of 20. What I tried to code (but failed) was that if a player (say player 1) reaches 20 it stops that player’s part of code and keeps the other player’s (player 2) code running until he reaches 20 aswell and then displays who reached 20 first.

import random

player1 = 0
rollnum_player1 = 0       
player2 = 0   
rollnum_player2 = 0        

def die():
    roll = random.randint(1,6)
    return roll



while True:
    
    # Player 1 code
    player1 += die()
    print("Player 1 roll:",player1)
    rollnum_player1 += 1
    if player1 >= 20:
        print("Congratulations player 1 you have won!")
        break

    # Player 2 code
    player2 += die()
    print(player2)
    rollnum_player2 += 1
    if player2 >= 20:
        print("Congratulations player 2 you have won!")
        break

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of breaking when a player wins, use if statements to skip over the code for the player who has already won. Break out of the loop when both have reached 20.

while player1 < 20 or player2 < 20:
    if player1 < 20:
        # Player 1 code
        player1 += die()
        print("Player 1 roll:",player1)
        rollnum_player1 += 1

    if player2 < 20:
        # Player 2 code
        player2 += die()
        print("Player 2 roll:",player2)
        rollnum_player2 += 1

if rollnum_player1 < rollnum_player2:
    print("Congratulations player 1 you have won!")
elif rollnum_player2 < rollnum_player1:
    print("Congratulations player 2 you have won!")
else:
    print("It's a tie!")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading